2
下面是我的代碼,我試圖變成一個Windows服務。你會看到test.py作爲它的調用,並且這是一個寫入日誌文件(作爲測試)的短腳本。Python程序作爲Windows服務
代碼是在那裏使它成爲一個Windows服務,它做得很好,但是當我運行它沒有寫入日誌文件。非常感謝。下面是代碼:
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time
class aservice(win32serviceutil.ServiceFramework):
_svc_name_ = "MyServiceShortName"
_svc_display_name_ = "A python test"
_svc_description_ = "Writing to a log"
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):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = 1000 #1 seconds
# This is how long the service will wait to run/refresh itself (see script below)
while 1:
# 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:
#what to run
try:
file_path = "test.py"
execfile(file_path)
except:
pass
#end of what to run
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(aservice)
編輯:思想爲它的緣故,我想包括我test.py文件的代碼,它有必要進口,但會完成這項工作,如果你單獨運行它。
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os
logfile = open("log.txt", "a") #open file to log restart timestamp
logfile.write("\nthat's good!!!!")
logfile.close()
確切的說'while 1:'code block?它看起來像是在班級的頂層。這是合法的嗎?你能再次檢查縮進並確保一切看起來正確嗎? – sarnold
您是否嘗試過指定日誌文件的路徑?我不確定服務「運行」在哪個目錄中。 –
@andrewcooke是的,即使只是撥打電話,我也嘗試了幾種不同的方式。例如,取出file_pat =「test.py」並放置一個打印語句或日誌記錄方法。 – user1399840