首先
pip install pywin32
写代码:(网上代码很多)
#ZPF
#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"
_svc_description_ = "This is a python service test code "
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 running ! ! !")
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)
实例化win32serviceutil.ServiceFramework的时候,windows系统会自动调用SvcDoRun方法,
这个函数的执行不可以结束,因为结束就代表服务停止。
当停止服务的时候,系统会调用SvcDoStop函数,该函数通过设置标志位等方式让SvcDoRun函数退出,就是正常的停止服务。
win32event.SetEvent(self.hWaitStop) 通过事件退出
服务的操作命令
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
启动前需要将下面两个库的绝对路径添加到系统环境变量:
Python37\Lib\site-packages\pywin32_system32;
Python37\site-packages\win32
;
如下:
管理员运行CMD 进行安装启动