本文摘自:https://blog.csdn.net/alex_bean/article/details/77924498
添加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 写Windows Service服务程序 http://www.cnblogs.com/dcb3688/p/4496934.html
“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill
标 题:Python 添加windows server服务程序