How do you run a Python script as a service in Windows?

后端 未结 13 1834
你的背包
你的背包 2020-11-22 02:18

I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which prov

13条回答
  •  臣服心动
    2020-11-22 02:31

    Step by step explanation how to make it work :

    1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : "c:\PythonFiles\AppServerSvc.py"

    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):
            win32serviceutil.ServiceFramework.__init__(self,args)
            self.hWaitStop = win32event.CreateEvent(None,0,0,None)
            socket.setdefaulttimeout(60)
    
        def SvcStop(self):
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            win32event.SetEvent(self.hWaitStop)
    
        def SvcDoRun(self):
            servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
            self.main()
    
        def main(self):
            # Your business logic or call to any class should be here
            # this time it creates a text.txt and writes Test Service in a daily manner 
            f = open('C:\\test.txt', 'a')
            rc = None
            while rc != win32event.WAIT_OBJECT_0:
                f.write('Test Service  \n')
                f.flush()
                # block for 24*60*60 seconds and wait for a stop event
                # it is used for a one-day loop
                rc = win32event.WaitForSingleObject(self.hWaitStop, 24 * 60 * 60 * 1000)
            f.write('shut down \n')
            f.close()
    
    if __name__ == '__main__':
        win32serviceutil.HandleCommandLine(AppServerSvc)
    

    2 - On this step we should register our service.

    Run command prompt as administrator and type as:

    sc create TestService binpath= "C:\Python36\Python.exe c:\PythonFiles\AppServerSvc.py" DisplayName= "TestService" start= auto

    the first argument of binpath is the path of python.exe

    second argument of binpath is the path of your python file that we created already

    Don't miss that you should put one space after every "=" sign.

    Then if everything is ok, you should see

    [SC] CreateService SUCCESS

    Now your python service is installed as windows service now. You can see it in Service Manager and registry under :

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TestService

    3- Ok now. You can start your service on service manager.

    You can execute every python file that provides this service skeleton.

提交回复
热议问题