2009-06-16 40 views
2

当您启动/停止python cherrypy服务(使用py2exe编译)时,此工作正常当我得到一个sys.exit()调用(来自我的错误处理程序)时,cherrypy退出,但服务仍然存在挂。在cherrypy服务中处理sys.exit()

代码:

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) 

任何意见将是巨大的:)

回答

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()