Python 3 Windows Service仅在调试模式下启动 [英] Python 3 Windows Service starts only in debug mode

查看:211
本文介绍了Python 3 Windows Service仅在调试模式下启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先在这篇文章中发布了答案,但它与论坛标准。我希望这次的回答符合论坛的标准。这段代码应该更清晰易读。

I first posted an answer in this post, but it didn't conform to the forum standards. I hope this time te answer fits the forum standards. This code should be more clear and easy to read.

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

In Python 3+ I have the following class that I use to build a Windows Service (it does nothing, just writes a log file):

#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 ,程序运行得很好(已写入日志文件),但是我仍然无法控制该服务:如果我打开另一个提示并尝试停止/启动服务,我仍然得到与上述相同的结果。

In the script I use a log file to check if it's working properly. I'm running python3.6 (also tried with python3.4) on Windows 7 and I'm experiencing the following problem. When I run python MyWindowsService.py install the prompt says that the service has been installed (but nothing is written in the log file). If I try to start the service, I get Service Error: 1 - More info NET HELPMSG 3547 which doesn't say much about the error. If I run python MyWindowsService.py debug, the program runs just fine (the log file is written), but still I don't have any control over the service: if I open another prompt and try to stop/start the service I still got the same results as stated above.

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

I also tryed to insert some debug code inside the init function, and when I run python MyWindowsService.py install it seems it doesn't get called. Is it possible?

我已经在网上检查了多种解决方案和变通办法,但没有找到合适的解决方案。我缺少什么?

I've checked for multiple solution and workarounds around the net, but I didn't find anything suitable. What am I missing?

推荐答案

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

As pointed out by eriksun in the comment to the first post, the problem came from the location of the python script, that was in a drive mapped with an UNC path - I'm working with a virtual machine. Moving the python script in the same drive as the python installation did the job. To sum it up for future uses, if the service fails to start and you're pretty sure about your code, these are helpful actions to try and solve your issues:


  • 使用 sc启动ServiceName sc查询ServiceName sc停止ServiceName 以获取有关服务的信息。

  • 检查文件是在物理驱动器中还是在UNC映射的驱动器中。如果后者尝试使用UNC路径运行脚本(例如 python \\Server\share\python\your-folder\script.py )或将脚本与python安装安装在同一驱动器中

  • 请确保符号链接了 python36.dll, vcruntime140.dll和 pywintypes36.dll到具有PythonService.exe的目录;或符号链接到System32目录;或具有这些DLL的目录位于系统(而非用户)路径中

  • 使用命令 reg查询HKLM\System\CurrentControlSet\检查系统注册Services\your_service_name / s 获取有关脚本的更多信息

  • use sc start ServiceName, sc query ServiceName and sc stop ServiceName to get info about the service.
  • check if your file is in a physical drive or in a UNC-mapped drive. If the latter try to run the script using the UNC path (for example python \\Server\share\python\your-folder\script.py) or move your script in the same drive as the python installation
  • make sure that "python36.dll", "vcruntime140.dll", and "pywintypes36.dll" are either symlink'd to the directory that has PythonService.exe; or symlink'd to the System32 directory; or that the directories with these DLLs are in the system (not user) Path
  • Check the system register with command reg query HKLM\System\CurrentControlSet\Services\your_service_name /s to get more information about the script

请轻松完成操作,更改,修改最后一个,这样对于像我这样的人来说,可以解决这个问题。

PLease, feel free to complete, change, modify the last so that it can be usefull for anyone that like me encounder this issue.

编辑:还有一件事...我的项目被认为实际上可以与网络文件夹(和UNC映射的驱动器)一起使用,但是当我尝试使其运行时失败了作为服务。 我在中找到的Mark Russinovich的SysinternalsSuite 这篇文章。希望这可以帮助。

One more thing... My project was thought to work actually with network folders (and UNC-mapped drive) and it failed when I tried to make it run as service. One very useful (day-saving) resource that I used to make it work is the SysinternalsSuite by Mark Russinovich that I found in this post. Hope this helps.

这篇关于Python 3 Windows Service仅在调试模式下启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆