【发布时间】:2011-12-17 08:14:48
【问题描述】:
我使用this question 来学习如何使用 ActivePython 将我的 python 脚本安装为服务。正如我所期望的那样,我能够安装和删除我的脚本,但我的问题是,一旦我开始运行脚本,我就失去了停止或删除它的能力。它只是永久运行,我无法摆脱它。链接问题的答案提到检查标志以停止脚本。有人能解释一下怎么做吗?
现在脚本做的很少。每隔几秒钟就将行打印到文件中。我想在处理更复杂的事情之前让它工作。
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import time
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "PythonTest"
_svc_display_name_ = "Python Test"
_svc_description_ = "This is a test of installing Python services"
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):
i=0
while True:
f=open("C:\\hello.txt","a")
f.write("hello"+str(i)+"\n")
f.close()
i=i+1
time.sleep(5)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
【问题讨论】:
-
我可能会建议 this ActiveState recipe 大大简化了编写简单的 Windows 服务。
标签: python windows service activepython