I recently had a Python program that needed to be installed and run as a Windows system service, and I ran into some pitfalls in the process, so I organized it.
Python Service Classes
First the Python program needs to call some Windows system APIs in order to act as a system service, as follows:
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import win32api import win32event import win32service import win32serviceutil import servicemanager class MyService(): _svc_name_ = "MyService" _svc_display_name_ = "My Service" _svc_description_ = "My Service" def __init__(self, args): ('init') .__init__(self, args) self.stop_event = (None, 0, 0, None) def SvcDoRun(self): (win32service.SERVICE_START_PENDING) try: (win32service.SERVICE_RUNNING) ('start') () ('wait') (self.stop_event, ) ('done') except BaseException as e: ('Exception : %s' % e) () def SvcStop(self): (win32service.SERVICE_STOP_PENDING) ('stopping') () ('stopped') (self.stop_event) (win32service.SERVICE_STOPPED) def start(self): (10000) def stop(self): pass def log(self, msg): (str(msg)) def sleep(self, minute): ((minute*1000), True) if __name__ == "__main__": if len() == 1: () (MyService) () else: (MyService)
Pyinstaller Packaging
pyinstaller -F
test (machinery etc)
# Installation services dist\ install # Start the service sc start MyService # Discontinued services sc stop MyService # Delete services sc delete MyService
This is the whole content of this article.