Python 3 Windows服务仅在调试模式下启动

时间:2017-03-04 18:27:29

标签: python windows python-3.x debugging service

我首先在this post中发布了答案,但它并不符合论坛标准。我希望这次回答符合论坛标准。此代码应更清晰易读。

在Python 3+中,我有以下用于构建Windows服务的类(它什么都不做,只写一个日志文件):

#MyWindowsService.py
import win32serviceutil
import servicemanager
import win32service
import win32event
import sys
import logging
import win32api


class MyWindowsService(win32serviceutil.ServiceFramework):
    _svc_name_          = 'ServiceName'
    _svc_display_name_  = 'Service Display Name'
    _svc_description_   = 'Service Full Description'
    logging.basicConfig(
        filename    = 'c:\\Temp\\{}.log'.format(_svc_name_),
        level       = logging.DEBUG,
        format      = '%(levelname)-7.7s @ %(asctime)s: %(message)s'
    )

    def __init__(self, *args):
        self.log('Initializing service {}'.format(self._svc_name_))
        win32serviceutil.ServiceFramework.__init__(self, *args)
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
        try:
            self.log('START: Service start')
            self.ReportServiceStatus(win32service.SERVICE_RUNNING)
            self.start()
            win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
        except Exception as e:
            self.log('Exception: {}'.format(e))
            self.SvcStop()

    def SvcStop(self):
        self.log('STOP: Service stopping...')
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.stop()
        win32event.SetEvent(self.stop_event)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def log(self, msg):
        servicemanager.LogInfoMsg(str(msg))  #system log
        logging.info(str(msg))               #text log

    def start(self):
        self.runflag = True
        while self.runflag:
            win32api.Sleep((2*1000), True)
            self.log('Service alive')
    def stop(self): 
        self.runflag = False
        self.log('Stop received')




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

在脚本中,我使用日志文件来检查它是否正常工作。我在Windows 7上运行python3.6(也尝试使用python3.4),我遇到了以下问题。当我运行python MyWindowsService.py install时,提示符表示已安装该服务(但未在日志文件中写入任何内容)。如果我尝试启动该服务,我会收到服务错误:1 - 更多信息NET HELPMSG 3547,它没有说明错误。如果我运行python MyWindowsService.py debug,程序运行正常(写入日志文件),但我仍然无法控制服务:如果我打开另一个提示并尝试停止/启动服务我仍然得到与上述相同的结果。

我还尝试在 init 函数中插入一些调试代码,当我运行python MyWindowsService.py安装时,它似乎没有被调用。有可能吗?

我已经检查了网络上的多种解决方案和解决方法,但我没有找到合适的解决方案。我错过了什么?

1 个答案:

答案 0 :(得分:0)

正如eriksun在第一篇文章的评论中指出的,问题来自python脚本的位置,即在使用UNC路径映射的驱动器中 - 我正在使用虚拟机。将python脚本移动到与python安装相同的驱动器中完成了这项工作。 总结以备将来使用,如果服务无法启动并且您对代码非常肯定,这些是尝试解决问题的有用操作:

  • 使用sc start ServiceNamesc query ServiceNamesc stop ServiceName获取有关服务的信息。
  • 检查您的文件是在物理驱动器中还是在UNC映射的驱动器中。如果后者尝试使用UNC路径运行脚本(例如python \\Server\share\python\your-folder\script.py)或将脚本移动到与python安装相同的驱动器中
  • 确保“python36.dll”,“vcruntime140.dll”和“pywintypes36.dll”与具有PythonService.exe的目录符号链接;或符号链接到System32目录;或者具有这些DLL的目录在系统(而不是用户)Path
  • 使用命令reg query HKLM\System\CurrentControlSet\Services\your_service_name /s检查系统寄存器以获取有关脚本的更多信息

请随意完成,更改,修改最后一个,以便它对任何像我这样的人遇到此问题都有用。

编辑:还有一件事......我的项目被认为实际上与网络文件夹(和UNC映射的驱动器)一起工作,当我尝试将其作为服务运行时,它失败了。我用来使其工作的一个非常有用的(节省日常的)资源是我在SysinternalsSuite by Mark Russinovich中找到的this post。希望这可以帮助。