在cherrypy服务中处理sys.exit()

2 投票
2 回答
1546 浏览
提问于 2025-04-15 12:17

当你启动或停止一个用py2exe编译的Python cherrypy服务时,一切都运行得很好。但是当我在错误处理程序中调用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)

任何建议都非常欢迎 :)

2 个回答

1

在这个讨论中,有人建议使用 cherrypy.engine.exit() 来停止一个 CherryPy 服务器,而不是用 sys.exit()

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

撰写回答