Search code examples
pythonwindowsservicewindows-services

Windows service works when running through command line but not through Services


Following this guide I created a service from a python script and used "py [script name] install". The service was installed successfully and I can see it in the services window. If I run the service through the command line using "py [script name] start", it all works correctly.

However, when I try to start it from the Windows Services window, it gives a different error depending on the account I use. All of these are suggestions I've seen on various forums:

1) Default (Local System Account)

When I try this one, it gives error "Windows could not start the service on Local Computer."

2) The admin account, which I'm running the cmd from

Same error as above

3) LOCAL SERVICE

Gives "Error 5: Access is denied." even though I'm logged in as admin.

Does anyone know what could be causing this?

I also tried creating a .exe from the python script and adding that as a service using sc.exe. However, when I did that, I never got past "The service did not respond to the start or control request in a timely fashion." This error also occurred when running it from the CMD until I copied some files into a directory in the python installation.


Solution

  • I've never tried a python script as a service, so I can't speak to that directly.

    I do know that the "The service did not respond to the start or control request in a timely fashion." error is almost always an indication that the OnStart() callback to the service (looks like SvcDoRun in your case) starts a long running operation (e.g., while loop) that never returns. The OnStart() callback is expected to kick off a foreground thread that will keep the service running and then return. From my recollection, if OnStart() doesn't return in about 30 seconds or so, Windows kills the service as unresponsive, which trigger this particular error message.

    Another thing to look at is the event viewer. It may be that your service is throwing an exception that you're not seeing due to process isolation.