1. Create Windows Services with pywin32
pywin32
is a Python library that provides an interface to the Windows API and can be used to create and manage Windows services.
Install pywin32
pip install pywin32
Writing service code
Here is a simple Python script example for creating a Windows service:
import win32serviceutil import win32service import win32event import servicemanager import socket import time class MyService(): _svc_name_ = "MyPythonService" # Service Name _svc_display_name_ = "My Python Service" # display name _svc_description_ = "This is a Python-based Windows service." # Service Description def __init__(self, args): .__init__(self, args) = (None, 0, 0, None) self.is_alive = True def SvcStop(self): (win32service.SERVICE_STOP_PENDING) () self.is_alive = False def SvcDoRun(self): (servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) () def main(self): while self.is_alive: # Write your service logic here print("Service is running...") (5) if __name__ == '__main__': (MyService)
illustrate
-
_svc_name_
: The internal name of the service. -
_svc_display_name_
: The name displayed in Windows Service Manager. -
_svc_description_
: Service description information. -
SvcDoRun
: Logic running when the service starts up. -
SvcStop
: Logic running when the service stops.
2. Package Python scripts as exe
Use PyInstaller to package the above script into an exe file:
pyinstaller --onefile your_service_script.py
The generated exe file is located atdist
in the directory.
3. Installation service
usesc
Command to install the exe file as a Windows service:
sc create MyPythonService binPath= "C:\path\to\your_service_script.exe"
-
MyPythonService
: The name of the service. -
binPath
: The full path to the exe file.
4. Start the service
Start the service with the following command:
sc start MyPythonService
5. Stop and delete services
- Stop service:
sc stop MyPythonService
- Delete the service:
sc delete MyPythonService
6. Debugging Service
- If the service fails to start, you can view the Windows event log (
Event Viewer
Error message in ). - You can also add logging functionality to the service code for debugging.
7. Things to note
- Make sure your exe file has administrator privileges.
- If the service requires access to network or other system resources, make sure the correct permissions are configured.
- If the service needs to interact with the user, please use
win32service.SERVICE_INTERACTIVE_PROCESS
Logo.
Through the above steps, you can run the exe file packaged by Python scripts as a Windows service. If you encounter problems, please provide specific error information for further analysis.
The above is the detailed content of the process steps for making python packaged exe into Windows service. For more information about making python exe into Windows service, please pay attention to my other related articles!