以Windows Service的方式運行Python程序
Python程序代碼
- importwmi
- importos
- c=wmi.WMI()
- watcher=c.Win32_PowerManagementEvent.watch_for(EventType=7)#監(jiān)視待機事件的語句;
- whileTrue:
- os.system("kdlj.vbs")#運行“連接寬帶“的程序,這里還是用了上次那位仁兄的vbs代碼;
- watcher()
由于運行時Python程序的控制臺窗口一直在那兒,看著有點礙事兒。于是乎想到要是能把他以windowsservice的方式運行,就像其他在windows服務管理器里的程序一樣。
最終,在"PythonProgrammingOnWin32"(byMarkHammond)這本書里找到了相關(guān)介紹,它里
面有一個簡單的模版,把Python程序代碼放入相應位置就可以了:
- #SmallestService.py
- #
- #AsampledemonstratingthesmallestpossibleservicewritteninPython.
- importwin32serviceutil
- importwin32service
- importwin32event
- classSmallestPythonService(win32serviceutil.ServiceFramework):
- _svc_name_="SmallestPythonService"
- _svc_display_name_="ThesmallestpossiblePythonService"
- def__init__(self,args):
- win32serviceutil.ServiceFramework.__init__(self,args)
- #Createaneventwhichwewillusetowaiton.
- #The"servicestop"requestwillsetthisevent.
- self.hWaitStop=win32event.CreateEvent(None,0,0,None)
- defSvcStop(self):
- #Beforewedoanything,telltheSCMwearestartingthestopprocess.
- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
- #Andsetmyevent.
- win32event.SetEvent(self.hWaitStop)
- defSvcDoRun(self):
#把你的程序代碼放到這里就OK了
win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE)if__name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)
#括號里的名字可以改成其他的,必須與class名字一致;
接下來,只要安裝一下服務,cmd下運行:SmallestService.pyinstall就行了。
這樣,你就可以在windows服務管理器里找到一個名叫"ThesmallestpossiblePythonService"的服務了,設成自動啟動,就會開機自動啟動并且一直在后臺運行了。(眼不見心不煩,)
不過,這樣雖然達到目的了,但還是發(fā)現(xiàn)個小問題,就是要是想停止該服務,關(guān)閉的進度條就愣在那里不動了,必須在進程管理器里把pythonservice.exe關(guān)掉才行,這個bug一直沒法解決,就是關(guān)閉服務的同時,要把監(jiān)視待機事件取消,否則退不出這個死循環(huán)。要是哪位高人看到了,希望可以指點一二。
【編輯推薦】