windows service運行Python相關操作技巧分享
我們今天將要為大家介紹的是有關windows service運行Python的一些應用技巧。相信用過Python這一編程語言的朋友們都會發現這一門功能強大,簡單易用的程序語言,可以幫助我們輕松的實現許多功能需求。
- import wmi
- import os
- c = wmi.WMI()
- watcher = c.Win32_PowerManagementEvent.watch_for
(EventType=7) # 監視待機事件;- while True:
- os.system("kdlj.vbs") # 運行“連接寬帶“的程序,
這里還是用了上次那位仁兄的vbs代碼;- watcher()
由于windows service運行Python的控制臺窗口一直在那兒,看著有點礙事兒。于是乎想到要是能把他以windows service的方式運行,就像其他在windows服務管理器里的程序一樣。
最終,在"Python Programming On Win32"(by Mark Hammond)這本書里找到了相關介紹,它里面有一個簡單的模版,把程序代碼放入相應位置就可以了:
- # SmallestService.py
- #
- # A sample demonstrating the smallest possible service written in Python.
- import win32serviceutil
- import win32service
- import win32event
- class SmallestPythonService(win32serviceutil.ServiceFramework):
- _svc_name_ = "SmallestPythonService"
- _svc_display_name_ = "The smallest possible Python Service"
- def __init__(self, args):
- win32serviceutil.ServiceFramework.__init__(self, args)
- # Create an event which we will use to wait on.
- # The "service stop" request will set this event.
- self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
- def SvcStop(self):
- # Before we do anything, tell the SCM we are starting the stop process.
- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
- # And set my event.
- win32event.SetEvent(self.hWaitStop)
- def SvcDoRun(self):
- # 把你的程序代碼放到這里就OK了
- win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
- if __name__=='__main__':
- win32serviceutil.HandleCommandLine(SmallestPythonService)
- # 括號里的名字可以改成其他的,必須與class名字一致;
接下來,只要安裝一下服務,cmd下運行:SmallestService.py install 就行了。這樣,你就可以在windows服務管理器里找到一個名叫"The smallest possible Python Service"的服務了,設成自動啟動,就會開機自動啟動并且一直在后臺運行了。(眼不見心不煩,)
不過,這樣雖然達到windows service運行Python的目的了,但還是發現個小問題,就是要是想停止該服務,關閉的進度條就愣在那里不動了,必須在進程管理器里把pythonservice.exe關掉才行。
【編輯推薦】