python開(kāi)發(fā)windows服務(wù)程序程序,并設(shè)置開(kāi)機(jī)啟動(dòng)

admin Python評(píng)論490字?jǐn)?shù) 2269閱讀模式

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ù)里看

python開(kāi)發(fā)windows服務(wù)程序程序,并設(shè)置開(kāi)機(jī)啟動(dòng)

版權(quán)聲明:文章圖片資源來(lái)源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)留言刪除!!!
廣告也精彩
admin
  • 本文由 發(fā)表于 2023年7月27日 02:39:25
  • 轉(zhuǎn)載請(qǐng)務(wù)必保留本文鏈接:http://yudch.cn/10859.html
匿名

發(fā)表評(píng)論

匿名網(wǎng)友 填寫(xiě)信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: