2

当您启动/停止 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)

任何建议都会很棒:)

4

2 回答 2

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()
于 2009-07-03T22:55:49.797 回答
1

建议通过 http 停止cherrypy 服务器cherrypy.engine.exit()而不是sys.exit().

于 2011-11-21T10:36:01.510 回答