This article mainly for you in detail the Python production of Windows system services related materials, with a certain reference value, interested in small partners can refer to
Recently a Python program needs to be installed and run as a Windows system service, encountering some pits and tidying up a bit.
Python service class
First the Python program needs to invoke some Windows system APIs to serve as a system service, as follows:
#!/usr/bin/env python#-*-coding:utf-8-*-import sysimport timeimport win32apiimport win32eventimport Win32serviceimport win32serviceutilimport servicemanagerclass MyService (win32serviceutil. Serviceframework): _svc_name_ = "MyService" _svc_display_name_ = "my service" _svc_description_ = "My Service" def INI T (self, args): Self.log (' init ') 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. Reportservicestatus (Win32service. service_running) Self.log (' Start ') Self.start () self.log (' Wait ') win32event. WaitForSingleObject (Self.stop_event, win32event. INFINITE) Self.log (' Done ') except baseexception as E:self.log (' Exception:%s '% e) self. Svcstop () def svcstop (self): self. Reportservicestatus (Win32service. service_stop_pending) Self.log (' stopping ') self.stop () Self.log (' sTopped ') win32event. SetEvent (self.stop_event) self. Reportservicestatus (Win32service. service_stopped) def start (self): Time.sleep (10000) def stop (self): Pass def log (self, msg): ServiceManager. Loginfomsg (str (msg)) def sleep (self, minute): Win32API. Sleep ((minute*1000), True) if name = = "Main": If Len (sys.argv) = = 1:servicemanager. Initialize () ServiceManager. Preparetohostsingle (MyService) ServiceManager. StartServiceCtrlDispatcher () Else:win32serviceutil. Handlecommandline (MyService)
Pyinstaller Packaging
Pyinstaller-f myservice.py
Test
# Install service Dist\myservice.exe install# Start service sc start myservice# stop service sc stop myservice# Delete Service SC delete MyService