Creating a Windows service in Python and installing it using pywin32 can be accomplished by following these steps. pywin32 is a Python extension that provides access to many of the Windows APIs from Python.
Step 1: Install pywin32
First, ensure you have pywin32 installed. You can install it via pip:
pip install pywin32
Step 2: Create the Service Script
Below is a basic example of a Python script that defines a Windows service class. This script uses win32serviceutil, which is part of the pywin32 package.
Save the following code as my_service.py:
import win32serviceutil
import win32service
import win32event
import servicemanager
import time
class MyService(win32serviceutil.ServiceFramework):
_svc_name_ = "MyPythonService"
_svc_display_name_ = "My Python Service"
_svc_description_ = "This is a sample service created in Python using pywin32."
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.running = True
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.running = False
def SvcDoRun(self):
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, "")
)
self.main()
def main(self):
while self.running:
servicemanager.LogInfoMsg("Service is running...")
time.sleep(5)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
Step 3: Install the Service
To install the service, run the following command in the same directory as my_service.py:
python my_service.py install
Step 4: Start the Service
To start the service, you can use the net start command or pywin32:
net start MyPythonService
Or:
python my_service.py start
Step 5: Stop the Service
To stop the service, you can use the net stop command or pywin32:
net stop MyPythonService
Or:
python my_service.py stop
Step 6: Remove the Service
If you need to remove the service, you can uninstall it with:
python my_service.py remove
Additional Notes:
- Logging and Debugging: The
servicemanager.LogMsg and LogInfoMsg functions are used to log messages to the Windows event log. This helps in debugging and monitoring your service.
- Error Handling: It's a good idea to add proper error handling in your
SvcDoRun and main methods to handle unexpected issues gracefully.
- Configuration: You can customize the service's behavior through the class attributes
_svc_name_, _svc_display_name_, and _svc_description_.
By following these steps, you can create, install, start, stop, and remove a Windows service written in Python using pywin32. This approach allows you to leverage Python's capabilities within the context of Windows services, making it easier to manage background processes and tasks on Windows systems.