windows service運(yùn)行Python相關(guān)操作技巧分享
我們今天將要為大家介紹的是有關(guān)windows service運(yùn)行Python的一些應(yīng)用技巧。相信用過(guò)Python這一編程語(yǔ)言的朋友們都會(huì)發(fā)現(xiàn)這一門(mén)功能強(qiáng)大,簡(jiǎn)單易用的程序語(yǔ)言,可以幫助我們輕松的實(shí)現(xiàn)許多功能需求。
- import wmi
- import os
- c = wmi.WMI()
- watcher = c.Win32_PowerManagementEvent.watch_for
(EventType=7) # 監(jiān)視待機(jī)事件;- while True:
- os.system("kdlj.vbs") # 運(yùn)行“連接寬帶“的程序,
這里還是用了上次那位仁兄的vbs代碼;- watcher()
由于windows service運(yùn)行Python的控制臺(tái)窗口一直在那兒,看著有點(diǎn)礙事兒。于是乎想到要是能把他以windows service的方式運(yùn)行,就像其他在windows服務(wù)管理器里的程序一樣。
最終,在"Python Programming On Win32"(by Mark Hammond)這本書(shū)里找到了相關(guān)介紹,它里面有一個(gè)簡(jiǎn)單的模版,把程序代碼放入相應(yīng)位置就可以了:
- # 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)
- # 括號(hào)里的名字可以改成其他的,必須與class名字一致;
接下來(lái),只要安裝一下服務(wù),cmd下運(yùn)行:SmallestService.py install 就行了。這樣,你就可以在windows服務(wù)管理器里找到一個(gè)名叫"The smallest possible Python Service"的服務(wù)了,設(shè)成自動(dòng)啟動(dòng),就會(huì)開(kāi)機(jī)自動(dòng)啟動(dòng)并且一直在后臺(tái)運(yùn)行了。(眼不見(jiàn)心不煩,)
不過(guò),這樣雖然達(dá)到windows service運(yùn)行Python的目的了,但還是發(fā)現(xiàn)個(gè)小問(wèn)題,就是要是想停止該服務(wù),關(guān)閉的進(jìn)度條就愣在那里不動(dòng)了,必須在進(jìn)程管理器里把pythonservice.exe關(guān)掉才行。
【編輯推薦】