Python3编写Windows服务程序

最近做了公司签到的小工具,有同事要求做成Windows服务,开机自启。先说下怎么用Python写Windows服务程序。

 1 #encoding=utf-8
 2 import win32serviceutil
 3 import win32service
 4 import win32event
 5 import win32timezone
 6 import os
 7 
 8 class PythonService(win32serviceutil.ServiceFramework):
 9     _svc_name_ = 'PythonService' #服务名称
10     _svc_display_name_ = 'regMeal'
11     _svc_description_ = '每天晚上6:40后自动签到'
12 
13 
14     def __init__(self,args):
15         win32serviceutil.ServiceFramework.__init__(self,args)
16         self.hWaitStop = win32event.CreateEvent(None,0,0,None)
17         self.logger = self._getLogger()
18         self.run = True
19 
20     def _getLogger(self):
21         import inspect
22         import logging
23         logger = logging.getLogger('[PythonService]')
24         this_file = inspect.getfile(inspect.currentframe())
25         dirpath = os.path.abspath(os.path.dirname(this_file))
26         handler = logging.FileHandler(os.path.join(dirpath,'service.log'))
27         formatter = logging.Formatter('%(asctime)s  %(name)-12s %(levelname)-8s %(message)s')
28         handler.setFormatter(formatter)
29         logger.addHandler(handler)
30         logger.setLevel(logging.INFO)
31         return logger
32 
33     def SvcDoRun(self):
34         import time
35         import readconfig
36         import regMeal
37         self.logger.info('service is run...')
38         while self.run:
39             self.logger.info('service is running...')
40             paraList = readconfig.readConfig()
41             bFlag = regMeal.main(paraList[0],paraList[1],paraList[2])
42             time.sleep(2)
43 
44     def SvcStop(self):
45         self.logger.info('service is stop.')
46         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
47         win32event.SetEvent(self.hWaitStop)
48         self.run = False
49 
50 if __name__ == '__main__':
51     import sys
52     import servicemanager
53     if len(sys.argv) == 1:
54         try:
55             evtsrc_dll = os.path.abspath(servicemanager.__file__)
56             servicemanager.PrepareToHostSingle(PythonService)
57             servicemanager.Initialize('PythonService',evtsrc_dll)
58             servicemanager.StartServiceCtrlDispatcher()
59         except win32service.error as details:
60             import winerror
61             if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
62                 win32serviceutil.usage()
63     else:
64         win32serviceutil.HandleCommandLine(PythonService)

推荐大家对比网上其他的人的代码对照看下。SvcDoRun这个函数里面放的就是你实际想做的事情。

安装服务

python PythonService.py install

让服务自动启动

python PythonService.py --startup auto install 

启动服务

python PythonService.py start

重启服务

python PythonService.py restart

停止服务

python PythonService.py stop

删除/卸载服务

python PythonService.py remove

我自己是用pyinstaller打包成exe给别人用的。

PS:脚本编好之后,调试了很久。刚开始会报服务无法启动的问题。具体的排查方式可以看Windows事件查看。

原文地址:https://www.cnblogs.com/gig886/p/7240630.html