pywin32编写的windows服务可以正常运行,使用pyinstaller打包后报错的解决办法
最近在做一个项目时需要编写windows服务,我使用conda管理的python3.8安装和启动pywin32编写的服务没有问题,但使用pyinstaller打包后就无法正常启动服务了,
在网上找了很多解决办法都没有解决,最后通过分析源代码和调试最终解决了这个问题,在这里记录一下。
源代码
# encoding=utf-8
import win32serviceutil
import win32service
import win32event
import os
import logging
class PythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonService"
_svc_display_name_ = "AAA Python Service"
_svc_description_ = "这是一段python服务代码"
_exe_name_ = "pythonservice.exe" # pythonservice.exe文件拷贝到当前目录
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]')
dir_path = os.path.relpath(os.path.dirname(__file__))
handler = logging.FileHandler(os.path.join(dir_path, "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)
使用pyinstaller打包
pyinstaller.exe -D -c --hidden-import win32timezone MyPythonService.py
之后将MyPythonService.py
和pythonservice.exe
两个文件放到打包生成的目录中(pythonservice.exe
文件可在python安装路径\Lib\site-packages\win32
中找到)
最后需设置环境变量,在系统变量中添加变量,变量名为PYTHONHOME
,变量值为python安装路径
验证
在命令行中切换到打包生成的目录中输入下面的命令进行安装和启动服务
MyPythonService install
MyPythonService start
然后打开服务查看该服务是否启动成功,可通过WIN+R打开运行窗口输入services.msc
进行查看。
pywin32服务操作命令
#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
注意
我使用的python版本为python3.8,windows版本为Windows 10 专业版
64位,其他版本可能有问题。
文章编写于2023年11月