下面是我试图将其转换为 Windows 服务的代码。您将看到 test.py 作为它进行的调用,所有这些都是一个写入日志文件的简短脚本(作为测试)。
代码是为了使其成为 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()
最佳答案
好吧,我想通了,并且想回来发帖以防其他人正在处理这个问题,尽管这有点独特。
如果你在 Windows 服务中,你必须指定你的文件路径,呃...但它没有完成,我无缘无故地拔了我的头发。
file_path = "test.py"
应该是
file_path = r"c:\users\...\test.py"
在 Windows 文件路径中使用“\”时要小心。它们必须像 '\\' 一样进行转义,或者必须将字符串声明为原始字符串 ('r')。使用类似于 unix 的斜杠“/”分隔符也可以,但对于 Windows 用户来说可能看起来很奇怪。
关于Python 程序作为 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10628377/