Python編寫Windows Service服務(wù)程序
如果你想用Python開發(fā)Windows程序,并讓其開機(jī)啟動(dòng)等,就必須寫成windows的服務(wù)程序Windows Service,用Python來做這個(gè)事情必須要借助第三方模塊pywin32,自己去下載然后安裝(注意下載符合自己OS的版本)。
1.示例分析
1).幸運(yùn)的是這里有一個(gè)簡(jiǎn)單的服務(wù)模版,足以滿足大多數(shù)人的要求:
#encoding=utf-8
#ZPF
import win32serviceutil
import win32service
import win32event
class PythonService(win32serviceutil.ServiceFramework):
#服務(wù)名
_svc_name_ = "PythonService"
#服務(wù)在windows系統(tǒng)中顯示的名稱
_svc_display_name_ = "Python Service Test"
#服務(wù)的描述
_svc_description_ = "This code is a Python service Test"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
# 把自己的代碼放到這里,就OK
# 等待服務(wù)被停止
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
def SvcStop(self):
# 先告訴SCM停止這個(gè)過程
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# 設(shè)置事件
win32event.SetEvent(self.hWaitStop)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(PythonService)
#括號(hào)里參數(shù)可以改成其他名字,但是必須與class類名一致;
2).解釋一下這段代碼:在類PythonService的__init__函數(shù)執(zhí)行完后,系統(tǒng)服務(wù)開始啟動(dòng),windows系統(tǒng)會(huì)自動(dòng)調(diào)用SvcDoRun函數(shù),這個(gè)函數(shù)的執(zhí)行不可以結(jié)束,因?yàn)榻Y(jié)束就代表服務(wù)停止。所以當(dāng)我們放自己的代碼在SvcDoRun函數(shù)中執(zhí)行的時(shí)候,必須確保該函數(shù)不退出,如果退出或者該函數(shù)沒有正常運(yùn)行就表示服務(wù)停止,windows系統(tǒng)會(huì)提示:

3).當(dāng)停止服務(wù)的時(shí)候,系統(tǒng)會(huì)調(diào)用SvcDoStop函數(shù),該函數(shù)通過設(shè)置標(biāo)志位等方式讓SvcDoRun函數(shù)退出,就是正常的停止服務(wù)。例子中是通過event事件讓SvcDoRun函數(shù)停止等待,從而退出該函數(shù),從而使服務(wù)停止。
4).注意:系統(tǒng)關(guān)機(jī)時(shí)不會(huì)調(diào)用SvcDoStop函數(shù),所以這種服務(wù)是可以設(shè)置為開機(jī)自啟的。
2.實(shí)例
一般都是通過在SvcDoRun函數(shù)中設(shè)置循環(huán)來達(dá)到不退出的目的,看例子通過設(shè)置標(biāo)志位run來實(shí)現(xiàn):
#ZPF
#encoding=utf-8
import win32serviceutil
import win32service
import win32event
import os
import logging
import inspect
class PythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonService"
_svc_display_name_ = "Python Service Test"
_svc_description_ = "This is a python service test code "
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.logger = self._getLogger()
self.run = True
def _getLogger(self):
logger = logging.getLogger('[PythonService]')
this_file = inspect.getfile(inspect.currentframe())
dirpath = os.path.abspath(os.path.dirname(this_file))
handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
def SvcDoRun(self):
import time
self.logger.info("service is run....")
while self.run:
self.logger.info("I am runing....")
time.sleep(2)
def SvcStop(self):
self.logger.info("service is stop....")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False
if __name__=='__main__':
win32serviceutil.HandleCommandLine(PythonService)
4.服務(wù)操作命令
下面是對(duì)上述服務(wù)操作的基本命令:
1.安裝服務(wù)
python PythonService.py install
2.讓服務(wù)自動(dòng)啟動(dòng)
python PythonService.py --startup auto install
3.啟動(dòng)服務(wù)
python PythonService.py start
4.重啟服務(wù)
python PythonService.py restart
5.停止服務(wù)
python PythonService.py stop
6.刪除/卸載服務(wù)
python PythonService.py remove
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django靜態(tài)文件配置request對(duì)象方法ORM操作講解
這篇文章主要為大家介紹了Django靜態(tài)文件配置request對(duì)象方法ORM操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
網(wǎng)易有道2017內(nèi)推編程題 洗牌(python)
這篇文章主要為大家詳細(xì)介紹了網(wǎng)易有道2017內(nèi)推編程題:洗牌,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06
python視頻轉(zhuǎn)化字節(jié)問題的完整實(shí)現(xiàn)
在Python中可以將視頻和字節(jié)進(jìn)行轉(zhuǎn)換,下面這篇文章主要給大家介紹了關(guān)于python視頻轉(zhuǎn)化字節(jié)問題的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
Python logging模塊異步線程寫日志實(shí)現(xiàn)過程解析
這篇文章主要介紹了Python logging模塊異步線程寫日志實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
django rest framework serializer返回時(shí)間自動(dòng)格式化方法
這篇文章主要介紹了django rest framework serializer返回時(shí)間自動(dòng)格式化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03

