python实现windows Service服务程序
win32serviceutil.ServiceFramework是封装得很好的Windows服务框架,本文通过继承它来实现。
- 通过SvcDoRun方法,实现服务启动,运行服务内的业务代码。
- 通过SvcStop方法,停止服务。
WinPollManager.py代码如下:
import win32serviceutil import win32service import win32event import winerror import servicemanager import time import sys import os class WinPollManager(win32serviceutil.ServiceFramework): """ #1.安装服务 python WinPollManager.py install #2.让服务自动启动 python WinPollManager.py --startup auto install #3.启动服务 python WinPollManager.py start #4.重启服务 python WinPollManager.py restart #5.停止服务 python WinPollManager.py stop #6.删除/卸载服务 python WinPollManager.py remove """ _svc_name_ = "py_agent_poll_manager" # 服务名 _svc_display_name_ = "py_agent_poll_manager" # 服务在windows系统中显示的名称 _svc_description_ = "python windows monitor agent" # 服务的描述 def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.isAlive = True self._poll_intvl = 30 def SvcDoRun(self): while self.isAlive: print 'monitor testing' time.sleep(self._poll_intvl) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isAlive = False if __name__ == '__main__': if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(WinPollManager) servicemanager.Initialize('WinPollManager', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error, details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(WinPollManager) # 括号里参数可以改成其他名字,但是必须与class类名一致;
打包exe文件
# -*- coding: utf-8 -*- """ pip install pyinstaller pyinstaller -F -w WinPollManager.py """ from PyInstaller.__main__ import run if __name__ == '__main__': params = ['WinPollManager.py', '-F', '-c', '--icon=favicon.ico'] run(params)
打包成功后在dist目录下生成exe文件
执行方式
- 安装服务 WinPollManager.exe install
- 服务自动启动 WinPollManager.exe –startup auto install
- 启动服务 WinPollManager.exe start
- 重启服务 WinPollManager.exe restart
- 停止服务 WinPollManager.exe stop
- 删除/卸载服务 WinPollManager.exe remove