andelf fledna Feather

2008年9月18日星期四

使用PyWin32将CherryPy应用安装为服务

CherryPy + PyWin32 应用 老版本的 cherrypy
# coding=cp936 import cherrypy import win32serviceutil import win32service import win32event
class HelloWorld: """ 请求句柄例子 """ # 暴露对象 @cherrypy.expose def index(self): # 只做测试用,所以只返回简单内容 return "Hello world!"
class MyService(win32serviceutil.ServiceFramework): """NT 服务""" # 服务名 _svc_name_ = "CherryPyService" # 服务显示名称 _svc_display_name_ = "CherryPy Service"
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # 创建一个事件 self.stop_event = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self): cherrypy.root = HelloWorld() # 更新配置,当使用配置文件时,必须为一个绝对路径 cherrypy.config.update({ 'global':{ 'server.socketPort' : 81, 'server.environment': 'production', 'server.logToScreen': False, 'server.log_file': 'e:\\edit\\log.txt', 'server.log_access_file': 'e:\\edit\\log.txt', 'autoreload.on' : False, 'server.logTracebacks' : True } }) # 设置 initOnly=True cherrypy.server.start(initOnly=True) win32event.WaitForSingleObject(self.stop_event, \ win32event.INFINITE) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) cherrypy.server.stop() win32event.SetEvent(self.stop_event)
if __name__ == '__main__': win32serviceutil.HandleCommandLine(MyService)
P.S.假设文件名为mysrv.py 则
x:\> mysrv.py --显示所有可用命令选项
mysrv.py install --安装服务
mysrv.py start --启动服务
mysrv.py stop --停止服务
mysrv.py restart --就是restart,重启,更新代码用
mysrv.py remove --删除服务
再P.S.测试时候一定要注意防火墙,服务是自动拦截的(pythonservice.exe).偶就在这里出问题了~嘻嘻
用到的路径必须全为绝对路径,静态目录也是
安装好服务后,也可以使用net start/stop CherryPyService 来管理