Running a Python Script as a Windows Service

Solution found on this blog: http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html

Suppose you want to turn a script called myscript.py into a service.

  1. Install Win2K Resource Kit (or copy the 2 binaries instsrv.exe and srvany.exe). The full Resource Kit can be found here: http://www.microsoft.com/downloads/
  2. Run instsrv to install srvany.exe as a service with the name myscript: "C:\Program Files\Windows Resource Kits\Tools\instsrv" myscript "C:\Program Files\Windows Resource Kits\Tools\srvany.exe"
  3. Go to Computer Management -> Services or Control Panel -> Administrative Tools -> Services and make sure myscript is listed as a service. Make sure the Startup Type is Automatic. Also make sure that the service has the right permissions to access applications in your computer by double clicking on myscript and going to Log On.
  4. Create a myscript.bat file in e.g. C:\pyscripts with the following contents: C:\Python25\python C:\pyscripts\myscript.py (replace Python25 with your Python version)
  5. Create new registry entries for the new service.
    • run regedt32 and go to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlDataset\Services\myscript entry
    • add new key (Edit -> Add Key) called Parameters
    • add new entry for Parameters key (Edit -> Add Value) to set the Application name
      • Name should be Application
      • Type should be REG_SZ
      • Value should be path to myscript.bat, i.e. C:\pyscripts\myscript.bat
    • add new entry for Parameters key (Edit -> Add Value) to set the working directory
      • Name should be AppDir
      • Type should be REG_SZ
      • Value should be path to pyscripts directory, i.e. C:\pyscripts
  6. Reboot your computer.
  7. Test starting and stopping the myscript service in Computer Management-> Services or Control Panel -> Administrative Tools -> Services