Python 创建 Windows 服务

 1 # -*- coding:utf-8 -*-
 2 
 3 """
 4 Prepare:
 5     pip install pywin32 pyinstaller
 6 
 7 Build:
 8     pyinstaller -F --hidden-import=win32timezone windows_service\test_service.py
 9 
10 Install:
11     dist\test_service.exe install
12 
13 Service Manage:
14     sc start PythonService
15     sc stop PythonService
16   or
17     dist\test_service.exe start
18     dist\test_service.exe stop
19 
20 Uninstall:
21     sc delete PythonService
22   or
23     dist\test_service.exe remove
24 """
25 
26 import os
27 import sys
28 import time
29 import servicemanager
30 import win32serviceutil
31 import win32service
32 import win32event
33 import winerror
34 
35 
36 class WindowsService(win32serviceutil.ServiceFramework):
37     _svc_name_ = 'PythonService'
38     _svc_display_name_ = 'Python_Service'
39     _svc_description_ = 'Test the python implementation of the Windows service'
40 
41     def __init__(self, args):
42         win32serviceutil.ServiceFramework.__init__(self, args)
43         self.stop_event = win32event.CreateEvent(None, 0, 0, None)
44         self.run = True
45 
46     def SvcDoRun(self):
47         with open(r"D:\tmp\start.log", "a") as fp:
48             fp.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
49             fp.write("\n")
50 
51         self.ReportServiceStatus(win32service.SERVICE_RUNNING)
52         # win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
53 
54         # 服务工作代码
55         while True:
56             with open(r"D:\tmp\monitor.log", "a") as fp:
57                 fp.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
58                 fp.write("\n")
59             time.sleep(10)
60 
61     def SvcStop(self):
62         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
63         win32event.SetEvent(self.stop_event)
64         self.ReportServiceStatus(win32service.SERVICE_STOPPED)
65         self.run = False
66 
67 
68 if __name__ == '__main__':
69     if len(sys.argv) == 1:
70         try:
71             event_src_dll = os.path.abspath(servicemanager.__file__)
72             servicemanager.PrepareToHostSingle(WindowsService)
73             servicemanager.Initialize('WindowsService', event_src_dll)
74             servicemanager.StartServiceCtrlDispatcher()
75         except win32service.error as details:
76             if details.args[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
77                 win32serviceutil.usage()
78     else:
79         win32serviceutil.HandleCommandLine(WindowsService)

猜你喜欢

转载自www.cnblogs.com/munan-zhou/p/12365371.html