如何使用Python创建Windows服务

问题描述

我写了一个python脚本,它将作为Windows服务安装。下面是代码

df2 = df2.assign(ACCOUNT_NUMBER=df1.iloc[:,0],ISSUANCENO= df1.iloc[:,1])
df2
     ACCOUNT_NUMBER  ISSUANCENO  SEQUENCE_NUMBER
0  1007143737797943      448866       1007143737
1  1007143738206753      163026       1007143738
2  1007143739416658      202092       1007143739
3  1007143740424543      772829       1007143740
4  1007143741130461      124043       1007143741

我已经运行命令import datetime import logging from logging.handlers import RotatingFileHandler import os import time from random import randint import win32serviceutil import win32service import win32event import servicemanager import socket def setup_logger(logger_name,log_file,level=logging.ERROR): log_formatter = logging.Formatter('%(asctime)s %(message)s') my_handler = RotatingFileHandler(log_file,maxBytes=100 * 1024 * 1024,backupCount=5) my_handler.setFormatter(log_formatter) my_handler.setLevel(level) l = logging.getLogger(logger_name) l.handlers[:] = [] l.addHandler(my_handler) curr_path = os.getcwd() log_file = "F:\\Projects\\TestService\\logs\\application.log" setup_logger('debug',log_file) log = logging.getLogger('debug') class AppServerSvc(win32serviceutil.ServiceFramework): _svc_name_ = "test_service" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,None) socket.setdefaulttimeout(60) self.isrunning = False def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isrunning = False def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_@R_630_4045@ION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_,'')) self.isrunning = True self.main() def main(self): while self.isrunning: log.error("Running {}".format(randint(00,99))) time.sleep(10) if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) 来安装服务,并获得了正确的输出python test_service.py install。当我打开服务选项卡时,我可以在其中看到我的服务。当我单击启动服务时,出现以下错误

enter image description here

任何人都可以告诉我代码中有什么问题,原因是该代码无法启动服务。请帮忙。谢谢

更新:

我在Installing service test_service Service installed中以调试模式运行了该服务,并且看起来工作正常。但是从“服务”标签中,它不起作用并显示上述错误

cmd

启动服务时,它会给出相同的错误

> python test_service.py debug
      Debugging service test_service - press Ctrl+C to stop.
      Info 0x40001002 - The test_service service has started.

不确定为什么不运行,并且在调试模式下运行良好。请帮忙。

解决方法

任何面临此问题的人,只需复制pywintypes36.dll

来自Python36\Lib\site-packages\pywin32_system32

Python36\Lib\site-packages\win32

有用的命令:

  1. 安装服务:python app.py install

  2. 卸载服务:python app.py remove

  3. 启动服务:python app.py start

  4. 更新服务:python app.py update