1.環(huán)境設(shè)置
python要開(kāi)發(fā)windows程序,首先必須先安裝好pywin32,還要安裝pyinstaller
pip install pywin32 -i https://pypi.tuna.tsinghua.edu.cn/simple pip install pyinstaller -i
2.編寫(xiě)代碼
以下是通用的python編譯成windows服務(wù)程序的模板,不要問(wèn)我為什么,我也是網(wǎng)上找的,可在SvcDoRun編寫(xiě)自己的業(yè)務(wù)代碼
#encoding=utf-8 import win32serviceutil import win32service import win32event import os import logging import inspect class PySerTest(win32serviceutil.ServiceFramework): _svc_name_ = "PySerTest" _svc_display_name_ = "Py Service Test"#服務(wù)顯示的名稱,可以自己修改 _svc_description_ = "This is a python service test code "http://服務(wù)顯示的描述 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")) handler = logging.FileHandler("G:\\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): #在此編寫(xiě)自己的業(yè)務(wù)程序 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.ReportServiceStatus(win32service.SERVICE_STOPPED) self.run = False if __name__=='__main__': # win32serviceutil.HandleCommandLine(PythonService) import sys import servicemanager if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(PySerTest) #如果修改過(guò)名字,名字要統(tǒng)一 servicemanager.Initialize('PySerTest',evtsrc_dll) #如果修改過(guò)名字,名字要統(tǒng)一 servicemanager.StartServiceCtrlDispatcher() except win32service.error as details: import winerror if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(PySerTest) #如果修改過(guò)名字,名字要統(tǒng)一
3.假如保存之后的文件名為winService.py,運(yùn)行以下命令即可生成exe程序
pyinstaller -F winService.py
4.編譯成功后,可通過(guò)以下命令對(duì)服務(wù)進(jìn)行控制
winService.exe install //僅安裝服務(wù)程序 winService.exe --startup auto install //安裝服務(wù)程序,并設(shè)置開(kāi)機(jī)啟動(dòng) winService.exe start //啟動(dòng)服務(wù) winService.exe stop //停止服務(wù) winService.exe remove //移除服務(wù)
下面是我自己創(chuàng)建的服務(wù)程序,可在系統(tǒng)服務(wù)里看
版權(quán)聲明:文章圖片資源來(lái)源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)留言刪除!!!
評(píng)論