【问题标题】:python service restart (when compiled to exe)python服务重启(编译为exe时)
【发布时间】:2010-11-05 03:01:43
【问题描述】:

我有一个服务,如下:

"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""

import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__

__builtin__.theService = None

class HelloWorld:
    """ Sample request handler class. """

    def __init__(self):
        self.iVal = 0

    @cherrypy.expose
    def index(self):

        try:

            self.iVal += 1 

            if self.iVal == 5:
                sys.exit()
            return "Hello world! " + str(self.iVal) 

        except SystemExit:
            StopServiceError(__builtin__.theService)


class MyService(win32serviceutil.ServiceFramework):
    """NT Service."""

    _svc_name_ = "CherryPyService"
    _svc_display_name_ = "CherryPy Service"
    _svc_description_ = "Some description for this service"

    def SvcDoRun(self):
        __builtin__.theService = self
        StartService()


    def SvcStop(self):
        StopService(__builtin__.theService)


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)


def StopServiceError(classObject):
    classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    cherrypy.engine.exit()
    classObject.ReportServiceStatus(serviceStatus=win32service.SERVICE_STOPPED, win32ExitCode=1, svcExitCode=1)

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(MyService)

我希望 Windows 在 sys.ext() 导致服务退出时重新启动服务。有谁知道如何让它做到这一点?

【问题讨论】:

标签: python windows-services restart


【解决方案1】:

我遇到了完全相同的问题:尝试使用错误代码使基于 Python 的服务退出,以便服务框架可以重新启动它。我尝试了ReportServiceStatus(win32service.SERVICE_STOP_PENDING, win32ExitCode=1, svcExitCode=1)sys.exit(1) 的方法,但它们都没有提示Windows 重新启动服务,尽管后者在事件日志中显示为错误。我最终没有依赖服务框架,而是这样做了:

def SvcDoRun(self):
    restart_required = run_service() # will return True if the service needs
                                     # to be restarted
    if restart_required:
        subprocess.Popen('sleep 5 & sc start %s' % self._svc_name_, shell=True)

【讨论】:

  • os.kill(os.getpid(), signal.SIGABRT)
【解决方案2】:

一个非编程相关的选项:

可以配置 Windows 服务以进行恢复。选择service properties 窗口的recovery 标签。您可以在第一次、第二次或后续失败后选择Restart the Service

一个简单的想法 - 你为什么不放弃sys.exit() 电话?这样服务就可以继续运行,您不必重新启动它。如果您确实需要知道self.iVal 何时到达5,您可以向事件记录器报告(或许还可以重置计数器)。

【讨论】:

  • 我已经这样做了,但是一分钟后它仍然没有重新启动服务。
  • 在系统/服务控制管理器下的事件日志项中寻找线索。
  • @gimel,这个“非编程选项”不起作用。使用 py2exe 构建的 Python 服务在失败后不会重新启动,即使 Windows 已按照您建议的方式进行配置。
  • 这是在使用 pyinstaller 和 EXE 编译时唯一对我有用的东西。 os.kill(os.getpid(), signal.SIGABRT) 没用。如果程序本身没有以非零代码结束,sys.exit(-1) 仍然是必需的。
  • @rlat 您的评论不清楚。你究竟是如何让它发挥作用的?
猜你喜欢
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 1970-01-01
  • 2022-06-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
相关资源
最近更新 更多