首先必須清楚, 在使用python來創建windows服務, 需要使用pywin32類庫, 下載地址:http://sourceforge.net/projects/pywin32/
下面我們創建一個什么也不做的服務,代碼如下:
win32test.py
import win32serviceutil
import win32service
import win32event
class win32test(win32serviceutil.ServiceFramework):
_svc_name_ = "Python Win32 Service"
_svc_display_name_ = "Python Win32 Service"
_svc_description_ = "Just for a demo, do nothing."
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(win32test)
如果你想使用這個服務在啟動或者停用時候做點事, 那么就把你要實現的業務寫給對應的方法里SvcDoRun和SvcStop.
下面我們來使用py2exe來把我們上面的service創建成安裝文件, py2exe下載地址:
http://sourceforge.net/projects/py2exe/
setup.py
from distutils.core import setup
import py2exe
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "1.0.0"
self.company_name = "Founder Software Suzhou Co. Ltd."
self.copyright = "Copyright © 2009 Founder Software (Suzhou) Co., Ltd. "
self.name = "Jchem cartridge windows service"
myservice = Target(
description = 'foo',
modules = ['win32test'],
cmdline_style='pywin32',
icon_resources=[(1, "cartrigde.ico")]
)
options = {"py2exe":
{ "compressed": 1,
"bundle_files": 1
}
}
setup(
service=[myservice],
options = options,
zipfile = None,
windows=[{"script": "win32test.py"}],
)
下面就可以使用python setup.py py2exe命令來生成安裝文件了.
生成的安裝文件可以使用一下命令來執行控制服務:
win32test.exe install
win32test.exe start
win32test.exe stop
win32test.exe remove
posted on 2009-06-28 12:24
周銳 閱讀(1939)
評論(0) 編輯 收藏 所屬分類:
Python