使用Python写Windows Service服务程序

资料来源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:WindowsSysWOW64cmd.exe上右键,以管理员身份运行;

第二步:在此dos下,进到python项目目录,用pipenv shell进到当前项目虚拟环境下

 第三步:再次执行python PythonService.py install

(2)启动服务python PythonService.py start时报错

报错提示:  服务无法启动:服务没有及时响应启动或控制请求 。1053

解决方案:

把当前项目虚拟环境目录下的Libsite-packageswin32和Libsite-packagespywin32_system32目录添加到环境变量的系统变量中。

如下两个目录在当前项目虚拟环境目录

C:UsersAdministrator.virtualenvspywindwos-IdJ1nAi2Libsite-packagespywin32_system32

C:UsersAdministrator.virtualenvspywindwos-IdJ1nAi2Libsite-packageswin32;

5.使用pyinstaller打包exe
pyinstaller.exe -F -c PythonService.py


原文地址:https://www.cnblogs.com/hzjdpawn/p/14167087.html