When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a sys.exit()
call (from my error handler), cherrypy quits, but the service remains hanging.
Code:
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)
Any advice would be great :)
I'm not entirely sure where the sys.exit
call is coming from or what your preferred behavior is. When sys.exit
is called, however, it raises a SystemExit
exception. You can intercept this and continue on your way:
import sys
try:
sys.exit()
except SystemExit:
print "Somebody called sys.exit()."
print "Still running."
... or use finally
to do some cleanup:
try:
do_something()
finally:
cleanup()
stopping a cherrypy server over http recommends cherrypy.engine.exit()
instead of sys.exit()
.