Python脚本作为Windows服务

时间:2016-07-26 10:52:54

标签: python

我正在尝试在Windows 10中将我的python脚本作为Windows服务启动。为此,我在线跟踪了大量的指南,但我主要遇到Access denied 5.The service did not respond to the start or control request in a timely fashion以下是我启动它的方式:

import time
import requests
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket

class AppServerSvc (win32serviceutil.ServiceFramework):
    # you can NET START/STOP the service by the following name
    _svc_name_ = "Smartlab_heater"
    # this text shows up as the service name in the Service
    _svc_display_name_ = "Smartlab_heater"
    # this text shows up as the description in the SCM
    _svc_description_ = "This service gets data from Siemens server and sends it to Smartlab server"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        # create an event to listen for stop requests on
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    # called when we're being shut down 
    def SvcStop(self):
        # tell the SCM we're shutting down 
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # fire the stop event  
        win32event.SetEvent(self.hWaitStop)

    #CUSTOM FUNCTIONS HERE

    # core logic of the service 
    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STARTED,
                            (self._svc_name_,''))
        self.timeout = 20000     #20 seconds
        # This is how long the service will wait to run / refresh itself (see script below)a

        rc = None

        # if the stop event hasn't been fired keep looping  
        while True:
            # Wait for service stop signal, if I timeout, loop again
            rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
            # Check to see if self.hWaitStop happened
            if rc == win32event.WAIT_OBJECT_0:
                # Stop signal encountered
                servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!")  #For Event Log
                break
            else:
                #MY CODE HERE

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

我尝试像C:Loc\of\script>python script.py install

一样启动它

当我尝试启动它时,我拒绝访问。然后我读到了它可能的地方,因为我没有定义用户名和密码,因此我尝试了:C:Loc\of\script>python script.py install --username <my user name> -- password。(注意:Pass是空的,因为我不使用1)。

那么我做错了什么?

0 个答案:

没有答案