Before we move on to a more substantial service written in Python, let’s write the smallest possible service in Python. This service will do no actual work other than interact with the SCM.
The key points from this example code are:
The logic for stopping the service must be provided by your application. This sample service uses a Win32 event object and when the command to stop the service is received, it sets this event. The service itself does nothing other than wait for this event to be set.
The name of the service and the display name of the service must be provided by the subclass.
This code contains startup code that handles the command line when run as a script. This provides facilities for installing, debugging, and starting the service, as described in the next section.
# SmallestService.py # # A sample demonstrating the smallest possible service written in Python. import win32serviceutil import win32service import win32event class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "SmallestPythonService" _svc_display_name_ = "The smallest possible Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) ...