1. Installing Pywin32 and Pyinstaller
pip install pywin32pip install pyinstaller
2. Write a service Demo
#-*-Coding:utf-8-*-import sysimport timeimport win32apiimport win32eventimport win32serviceimport Win32serviceutilimport servicemanagerimport loggingimport inspectimport osclass MyService (win32serviceutil. Serviceframework): _svc_name_ = "MyService" _svc_display_name_ = "my service" _svc_description_ = "My Service" def __init__ (self, args): Win32serviceutil. Serviceframework.__init__ (self, args) self.stop_event = win32event. CreateEvent (None, 0, 0, none) Self.logger = Self._getlogger () def _getlogger (self): logger = Logging.getl Ogger (' [MyService] ') This_file = Inspect.getfile (Inspect.currentframe ()) Dirpath = Os.path.abspath (Os.path.d Irname (this_file)) handler = logging. Filehandler (Os.path.join (Dirpath, Self._svc_name_ + ". Log")) formatter = logging. Formatter ('% (asctime) s% (name) -12s% (levelname) -8s% (message) s ') Handler.setformatter (Formatter) LOGGER.ADDH Andler (handler) Logger.setlevel (logging. INFO) Return logger def svcdorun (self): self. Reportservicestatus (Win32service. service_start_pending) try:self. Reportservicestatus (Win32service. service_running) self.logger.info (' Start ... ') Self.start () self.logger.info (' Wait ... ') Win32event. WaitForSingleObject (Self.stop_event, win32event. INFINITE) self.logger.info (' done! ') Except Baseexception as E:self.logger.warn (' Exception:%s '% e) self. Svcstop () def svcstop (self): self. Reportservicestatus (Win32service. service_stop_pending) self.logger.info (' stopping ... ') self.stop () self.logger.info (' 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 *), True) if __name__ = = "__main__": If Len (sys.argv) = = 1:servicemanager. Initialize () ServiceManager. Preparetohostsingle (MyService) ServiceManager. StartServiceCtrlDispatcher () Else:win32serviceutil. Handlecommandline (MyService)
3. Freezing the binary
pyinstaller -F MyService.py --hidden-import=win32timezone
4. Running the service
dist\MyService.exe installsc start MyService
Write a Python Windows service