【发布时间】:2017-03-04 18:27:29
【问题描述】:
我首先在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 时,提示说服务已安装(但日志文件中没有写入任何内容)。如果我尝试启动该服务,我会收到 Service Error: 1 - More info NET HELPMSG 3547 ,这并没有说明该错误。如果我运行python MyWindowsService.py debug,程序运行得很好(日志文件被写入),但我仍然无法控制服务:如果我打开另一个提示并尝试停止/启动服务,我仍然得到结果与上述相同。
我还尝试在 init 函数中插入一些调试代码,当我运行 python MyWindowsService.py install 时,它似乎没有被调用。有可能吗?
我已经检查了网络上的多种解决方案和解决方法,但没有找到合适的。我错过了什么?
【问题讨论】:
-
尝试使用
sc start ServiceName启动服务。这可能会提供更多信息。另外,使用命令sc qc ServiceName查询配置。这应该显示“PythonService.exe”的完全限定路径。检查是否可以在命令提示符下运行它。如果没有,请确保将“python36.dll”、“vcruntime140.dll”和“pywintypes36.dll”符号链接到具有 PythonService.exe 的目录;或符号链接到 System32 目录;或者这些 DLL 的目录在系统中(不是用户)Path。 -
嗨 eryksun,感谢您的关注。
-
我检查了你提到的 dll 并将它们的目录添加到系统路径 - 没有任何改变。
sc start ServiceName返回STATUS 2 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)我还在系统路径中添加了“PythonService.exe”路径 - 以防万一,但同样没有发生任何事情。 -
这很正常。跟进
sc query ServiceName以查看当前状态。然后用sc stop ServiceName停止它。 -
sc query ServiceName返回STATUS: 1 STOPPED,WIN32_EXIT_CODE : 1066sc stop ServiceName返回FAILED 1062: Service not started
标签: python windows python-3.x debugging service