最近在把Python的定時(shí)程序放進(jìn)Windows服務(wù)時(shí)遇到了上述的問題‘錯(cuò)誤1053:服務(wù)沒有及時(shí)響應(yīng)啟動(dòng)或控制請(qǐng)求’ 或者 ‘Error 1053: The service did not respond to the start or control request in a timely fashion’庸追。
可以正常安裝python PythonFileName.py install
遥巴,
不能正常啟動(dòng)python PythonFileName.py start
捌臊。
嘗試使用python PythonFileName.py debug
檢查代碼爷恳,沒有發(fā)現(xiàn)代碼問題,考慮應(yīng)該是環(huán)境問題正蛙。
最終在StackOverflow的 Can't start Windows service written in Python (win32serviceutil) 中找到了 BuvinJ 的回答:“It might prove useful in this case to also add these directories to your system path: C:\Python27\Lib\site-packages\win32 and C:\Python27\Lib\site-packages\pywin32_system32. That will let you use pythonservice more easily. ”
解決辦法
在cmd中輸入
setx /M PATH "%PATH%;C:\Python27;C:\Users\Administrator\Anaconda2\Scripts;C:\Users\Administrator\Anaconda2\Lib\site-packages\pywin32_system32;C:\Users\Administrator\Anaconda2\Lib\site-packages\win32"
回車验夯,增加兩個(gè)路徑的引用魁蒜。然后就能啟動(dòng)服務(wù)了操刀。
具體的Windows服務(wù)Python代碼:
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager
import winerror
class StockRecommendRunLoop(win32serviceutil.ServiceFramework):
_svc_name_ = "StockRecommendRunLoop"
_svc_display_name_ = "Stock Recommend Run Loop"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start_task()
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__ == '__main__':
if len(sys.argv) == 1:
try:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(StockRecommendRunLoop)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error, details:
if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(StockRecommendRunLoop)
Reference:
Can't start Windows service written in Python (win32serviceutil)
Python Windows Service的方式運(yùn)行