Andrey Kogut
Andrey Kogut

Reputation: 33

Run Python script as a windows service failed

I'm trying to create and run a Windows service from Python code. Edition: Windows 10 Pro; Version: 21H1; OS build: 19043.1526

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?

Upvotes: 0

Views: 33

Answers (1)

Andrey Kogut
Andrey Kogut

Reputation: 33

I'm earch in google next:

python win32serviceutil.HandleCommandLine() [SC] StartService FAILED 1053:The service did not respond to the start or control request in a timely fashion.

Helped links:

Solution

I Step

Launched the console as an administrator

Installed pywin32 globally and locally within the project (.venv).

pip install pywin32

Then check installed package in C:\Python\Python313\Lib\site-packages

II Step

From C:\Python\Python313\Scripts run

python C:\Python\Python313\Scripts\pywin32_postinstall.py -install

III Step

Go to own python project with service

C:\Users\Projects\services>python win_service2.py --startup=auto install

This command displayed

Installing service MyWinSrv2
moving host exe 'C:\Python\Python313\Lib\site-packages\win32\pythonservice.exe' -> 'C:\Python\Python313\pythonservice.exe'
copying helper dll 'C:\Python\Python313\Lib\site-packages\pywin32_system32\pywintypes313.dll' -> 'C:\Python\Python313\pywintypes313.dll'
Service installed

That's it!

Service commands

python win_service2.py --startup=auto install
python win_service2.py start
python win_service2.py stop
python win_service2.py remove

Upvotes: 0

Related Questions