Python Language A Python script that can be run as a service


The modules used in this example are part of pywin32 (Python for Windows extensions). Depending on how you installed Python, you might need to install this separately.

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)

    def SvcStop(self):

    def SvcDoRun(self):

    def main(self):

if __name__ == '__main__':

This is just boilerplate. Your application code, probably invoking a separate script, would go in the main() function.

You will also need to install this as a service. The best solution for this at the moment appears to be to use Non-sucking Service Manager. This allows you to install a service and provides a GUI for configuring the command line the service executes. For Python you can do this, which creates the service in one go:

nssm install MyServiceName c:\python27\python.exe c:\temp\

Where is the boilerplate script above, modified to invoke your application script or code in the main() function. Note that the service doesn't run the Python script directly, it runs the Python interpreter and passes it the main script on the command line.

Alternatively you can use tools provided in the Windows Server Resource Kit for your operating system version so create the service.