参考来源 https://blog.csdn.net/weixin_34075551/article/details/94455359?utm_source=app
1.背景
如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装。
win32serviceutil.ServiceFramework是封装得很好的Windows服务框架,本文通过继承它来实现。
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_ = "Python Service Test" #服务在windows系统中显示的名称
_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.打包exe文件
# -*- coding: utf-8 -*-
"""
pip install pyinstaller
pyinstaller -F -w PythonService.py
"""
from PyInstaller.__main__ import run
if __name__ == '__main__':
params = ['PythonService.py', '-F', '-c', '--icon=favicon.ico']
run(params)
打包成功后在dist目录下生成exe文件
执行方式
本文分享自 Python数据分析实例 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!