# pywin32编写的windows服务可以正常运行,使用pyinstaller打包后报错的解决办法

文章讲述了作者在使用PyInstaller打包基于pywin32编写的Windows服务时遇到的问题,通过源代码分析和调试解决了打包后无法启动服务的问题,并提供了详细的步骤和注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.pypythonservice.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月

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值