当你启动/停止python cherrypy服务(使用py2exe编译)时,这工作正常当我收到sys.exit()
调用(来自我的错误处理程序)时,cherrypy退出,但服务仍然挂起。
代码:
import cherrypy
import win32serviceutil
import win32service
import sys
SERVICE = None
class HelloWorld:
""" Sample request handler class. """
def __init__(self):
self.iVal = 0
@cherrypy.expose
def index(self):
self.iVal += 1
if self.iVal == 5:
StopService(SERVICE)
return "Hello world! " + str(self.iVal)
class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""
_svc_name_ = "CherryPyService"
_svc_display_name_ = "CherryPy Service"
_svc_description_ = "Some description for this service"
def SvcDoRun(self):
SERVICE = self
StartService()
def SvcStop(self):
StopService(SERVICE)
def StartService():
cherrypy.tree.mount(HelloWorld(), '/')
cherrypy.config.update({
'global':{
'tools.log_tracebacks.on': True,
'log.error_file': '\\Error_File.txt',
'log.screen': True,
'engine.autoreload.on': False,
'engine.SIGHUP': None,
'engine.SIGTERM': None
}
})
cherrypy.engine.start()
cherrypy.engine.block()
def StopService(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(win32service.SERVICE_STOPPED)
if __name__ == '__main__':
print sys.argv
win32serviceutil.HandleCommandLine(MyService)
任何建议都会很棒:)
答案 0 :(得分:2)
我不完全确定sys.exit
来电的来源或您的首选行为。但是,当调用sys.exit
时,它会引发SystemExit
异常。你可以拦截这个并继续前进:
import sys
try:
sys.exit()
except SystemExit:
print "Somebody called sys.exit()."
print "Still running."
...或使用finally
进行一些清理:
try:
do_something()
finally:
cleanup()
答案 1 :(得分:1)
stopping a cherrypy server over http建议cherrypy.engine.exit()
代替sys.exit()
。