SoFunction
Updated on 2025-04-08

python windows services demo sharing

python windows services demo

Creating and managing services in Windows operating systems can be implemented in Python, usually usingpywin32library.

This library provides the functionality to access the Windows API, including creating and controlling Windows services.

Here is a simple example showing how to create a basic Windows service.

Installation dependencies

  • First, you need to install itpywin32library.
  • You can install it through pip:
pip install pywin32

Create a simple Windows service

  • Here is a basic Windows service sample code.
  • The service will print a message to the log file every 10 seconds.
import win32serviceutil
import win32service
import win32event
import servicemanager
import time
import logging

# Configure logging(
    filename='C:\\path_to_your_log_file\\my_service.log',
    level=,
    format='%(asctime)s %(levelname)-8s %(message)s'
)

class MyService():
    _svc_name_ = "MyPythonService"  # Service Name    _svc_display_name_ = "My Python Service"  # Service display name    _svc_description_ = "This is a demo service using Python."  # Service Description
    def __init__(self, args):
        .__init__(self, args)
         = (None, 0, 0, None)
        self.is_alive = True

    def SvcDoRun(self):
        (servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        ()

    def SvcStop(self):
        (win32service.SERVICE_STOP_PENDING)
        ()
        self.is_alive = False

    def main(self):
        while self.is_alive:
            ('Service is running...')
            (10)  # Execute every 10 seconds
if __name__ == '__main__':
    (MyService)

Things to note

Modify log path: Please make surefilename='C:\\path_to_your_log_file\\my_service.log'Replace with the actual path you want to store the log file.

Installation Service

  • Save the above code as a Python file (e.g.)。
  • Open a command prompt (administrator permissions) and navigate to the directory containing your Python scripts.
  • Use the following command to install the service:
python  install
  • If you need to uninstall the service, you can use:
python  remove

Start and stop service

  • The service can be started using the following command via the command prompt:
python  start
  • Stop service:
python  stop
  • It can also be done through the Windows Service Manager () to manage services.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.