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

admin Python評論495字?jǐn)?shù) 2269閱讀模式

1.環(huán)境設(shè)置

python要開發(fā)windows程序,首先必須先安裝好pywin32,還要安裝pyinstaller文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

pip install pywin32 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyinstaller -i

2.編寫代碼文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

以下是通用的python編譯成windows服務(wù)程序的模板,不要問我為什么,我也是網(wǎng)上找的,可在SvcDoRun編寫自己的業(yè)務(wù)代碼文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

#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):
        #在此編寫自己的業(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) #如果修改過名字,名字要統(tǒng)一
            servicemanager.Initialize('PySerTest',evtsrc_dll) #如果修改過名字,名字要統(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) #如果修改過名字,名字要統(tǒng)一

3.假如保存之后的文件名為winService.py,運行以下命令即可生成exe程序文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

pyinstaller -F winService.py

4.編譯成功后,可通過以下命令對服務(wù)進(jìn)行控制文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

winService.exe install    //僅安裝服務(wù)程序
winService.exe --startup auto install //安裝服務(wù)程序,并設(shè)置開機(jī)啟動
winService.exe start    //啟動服務(wù)
winService.exe stop     //停止服務(wù)
winService.exe remove    //移除服務(wù)

下面是我自己創(chuàng)建的服務(wù)程序,可在系統(tǒng)服務(wù)里看文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

python開發(fā)windows服務(wù)程序程序,并設(shè)置開機(jī)啟動文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html 文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10859.html

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

發(fā)表評論

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

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