資料來源https://blog.csdn.net/weixin_34075551/article/details/94455359?utm_source=app
1.背景
如果你想用Python開發Windows程序,並讓其開機啟動等,就必須寫成windows的服務程序Windows Service,用Python來做這個事情必須要借助第三方模塊pywin32,自己去下載然后安裝。
2.實例
# 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_ = "jlw Python Service Test" _svc_description_ = "這是一段python服務代碼 " 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)
解釋一下代碼:
1).在類PythonService的__init__函數執行完后,系統服務開始啟動,windows系統會自動調用SvcDoRun函數,這個函數的執行不可以結束,因為結束就代表服務停止。所以當我們放自己的代碼在SvcDoRun函數中執行的時候,必須確保該函數不退出。
2).當停止服務的時候,系統會調用SvcDoStop函數,該函數通過設置標志位等方式讓SvcDoRun函數退出,就是正常的停止服務。例子中是通過event事件讓SvcDoRun函數停止等待,從而退出該函數,從而使服務停止。系統關機時不會調用SvcDoStop函數,所以這種服務是可以設置為開機自啟的。
3.服務操作命令
#1.安裝服務 python PythonService.py install #2.讓服務自動啟動 python PythonService.py --startup auto install #3.啟動服務 python PythonService.py start #4.重啟服務 python PythonService.py restart #5.停止服務 python PythonService.py stop #6.刪除/卸載服務 python PythonService.py remove
4.報錯處理
(1)安裝服務python PythonService.py install時報錯
提示:安裝 py Error installing service: 拒絕訪問。 (5)
原因:權限不夠需要以管理員權限運行
解決方案:CDM管理員權限運行
具體方法:
第一步:先進到C:\Windows\SysWOW64\cmd.exe上右鍵,以管理員身份運行;
第二步:在此dos下,進到python項目目錄,用pipenv shell進到當前項目虛擬環境下
第三步:再次執行python PythonService.py install
(2)啟動服務python PythonService.py start時報錯
報錯提示: 服務無法啟動:服務沒有及時響應啟動或控制請求 。1053
解決方案:
把當前項目虛擬環境目錄下的Lib\site-packages\win32和Lib\site-packages\pywin32_system32目錄添加到環境變量的系統變量中。
如下兩個目錄在當前項目虛擬環境目錄
C:\Users\Administrator\.virtualenvs\pywindwos-IdJ1nAi2\Lib\site-packages\pywin32_system32
C:\Users\Administrator\.virtualenvs\pywindwos-IdJ1nAi2\Lib\site-packages\win32;
5.使用pyinstaller打包exe
pyinstaller.exe -F -c PythonService.py