我已經使用this question來學習如何使用ActivePython將我的python腳本安裝爲服務。我能夠安裝我的腳本並將其刪除,正如我所期望的那樣,但是我的問題是,一旦我啓動腳本運行,我就失去了停止或刪除腳本的能力。它只是永久運行,我無法擺脫它。鏈接問題的答案提到檢查標誌以停止腳本。有人可以解釋如何做到這一點?將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)
我可能會建議[此ActiveState配方](http://code.activestate.com/recipes/551780/)大大簡化了編寫簡單的Windows服務。 – ig0774