[Python] Run Python script as a windows service failed

Discussão em 'Python' iniciado por Stack, Fevereiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create and run a Windows service from Python code.

    from datetime import datetime
    import win32serviceutil
    import win32service
    import win32event
    import servicemanager
    import socket

    class Pythonservice(win32serviceutil.ServiceFramework):
    _svc_name_ = 'MyWindowsService2'
    _svc_display_name_ = 'MyWindowsService2'
    _svc_description_ = 'Friendly Service'

    def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
    self.isrunning = False

    def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    self.isrunning = False
    win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
    self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
    self.isrunning = True
    self.ReportServiceStatus(win32service.SERVICE_RUNNING)
    servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
    servicemanager.PYS_SERVICE_STARTED,
    (self._svc_name_, ''))
    self.main()

    def main(self):
    path = r"C:\Users\Documents\Projects\services\dist\Log.txt"
    while self.isrunning:
    rc = win32event.WaitForSingleObject(self.hWaitStop, 1000)
    if rc == win32event.WAIT_OBJECT_0:
    break
    try:
    with open(path, "w") as file:
    now = datetime.now().strftime("%B %d, %y %H:%M:%S")
    file.write(now)
    except Exception as e:
    servicemanager.LogMsg(servicemanager.EVENTLOG_ERROR_TYPE,
    servicemanager.PYS_SERVICE_STARTED,
    (f"Error: {str(e)}", ''))

    if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(Pythonservice)


    After that, I use pyinstaller to bundle it into an exe file:

    pyinstaller --onefile --hidden-import=win32timezone --hidden-import=pywintypes win_service2.py

    Then I successfully register the service:

    sc create MyWindowsService2 binPath="C:\Users\Documents\Projects\services\dist\win_service2.exe"

    Next, when I try to start it using the command: sc start MyWindowsService2

    I get the error:


    [SC] StartService FAILED 1053: The service did not respond to the start or control request in a timely fashion.
    ​

    I tried to execute the following after creating the service: .\dist\win_service2.exe start and python .\win_service2.py start

    but error:


    Starting service MyWindowsService2 Error starting service: The service did not respond to the request in a timely manner.
    ​

    I also tried registering the service using: sc create PythonApp binPath= "C:\Python\Python313\Python.exe --C:\Users\Documents\Projects\services\win_service2.py"

    But I got the same error.

    Please note that registration via nssm is not suitable!

    Question: Why does this error occur?

    Thanks a lot!

    Continue reading...

Compartilhe esta Página