简介
添加windows server服务,实现python程序开机自动
第三方库
pywin32
下载地址:https://pypi.python.org/pypi/pywin32
代码
# -*- coding: utf-8 -*-
import logging
import time
import win32service
import win32serviceutil
import win32event
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='e:/monitor/demo.log',
filemode='a')
servername = "DemoServer" # windows服务名称
# Demo.py 10秒关闭程序,模拟程序崩溃
# author 胖胖的alex 2017/09/10
class Demo:
def __init__(self):
pass
def execute(self):
logging.info("启动程序")
i = 1
while True:
logging.info("servername = " + servername + " ---------- run " + str(i) + " s ")
time.sleep(1)
i += 1
if i > 10:
break
logging.info("程序关闭...")
# 程序加入windows服务类
class Win32Server(win32serviceutil.ServiceFramework):
_svc_name_ = servername
_svc_display_name_ = servername
_svc_description_ = servername
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
logging.info("windows服务启动...")
rc = None
demo = Demo()
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
demo.execute()
time.sleep(2)
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
logging.info("windows服务关闭...")
# called when we're being shut down
def SvcStop(self):
# tell the SCM we're shutting down
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# fire the stop event
win32event.SetEvent(self.hWaitStop)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(Win32Server)
操作命令
- 安装:python PythonService.py install
- 自启动安装:python PythonService.py --startup auto install
- 启动服务:python PythonService.py start
- 重启服务:python PythonService.py restart
- 停止服务:python PythonService.py stop
- 卸载服务:python PythonService.py remove
注意事项
- 操作命令输入的控制台必须是管理员cmd
- 截至2017/09/10,pywin32支持python3.5或以下版本
参考文章
- Python 写Windows Service服务程序 http://www.cnblogs.com/dcb3688/p/4496934.html