posts - 431,  comments - 344,  trackbacks - 0

首先必须清楚, 在使用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 周锐 阅读(1920) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航: