持续集成除了第三方工具,还有计划任务,当然,也可以通过Windows服务来实现。
通过Python实现Windows服务,需要三方库win32,可以通过pip安装:pip install win32。
注意,安装完win32后,需要把两个路径加到系统路径,不然服务运行会出问题:
1、 \Python39\Lib\site-packages\pywin32_system32
2、 \Python39\Lib\site-packages\win32
下面就上代码:
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: AutoRunTest.py
Description : 本程序是实现Win服务,在晚上20点到23:59之间执行测试
Author : 曾良均
QQ: 277099728
Date: 10/8/2021 9:58 AM
-------------------------------------------------
Change Activity:
10/8/2021:
-------------------------------------------------
"""
__author__ = 'ljzeng'
from datetime import datetime
import win32serviceutil
import win32service
import win32event
import os
import servicemanager
import sys
import win32api
class AutoRunTest(win32serviceutil.ServiceFramework):
_svc_name_ = "AutoRunTestService" # 服务名
_svc_display_name_ = "AutoTestService" # Win服务上显示的名称
_svc_description_ = "IronIntel Automate testing services" # 服务描述
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.log('init')
def log(self, msg):
'''日志记录'''
servicemanager.LogInfoMsg(str(msg))
def start(self):
'''执行脚本'''
stime = datetime.strptime(str(datetime.now().date()) + '20:00', '%Y-%m-%d%H:%M')
endtime = datetime.strptime(str(datetime.now().date()) + '23:50', '%Y-%m-%d%H:%M')
now = datetime.now()
if stime < now < endtime:
self.log('running ... ')
re = os.popen("D:\\run.bat").read()
self.log(re)
else:
self.log('Not run time, wait ...')
def stop(self):
pass
def SvcDoRun(self):
while True:
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
nowtime = datetime.now().strftime("%Y.%m.%d %H:%M:%S.%f")[:-3]
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.log('%s -- start run' % nowtime)
self.start()
# win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # 手动停止服务
self.log('%s -- done' % nowtime)
except Exception as e:
self.log('Exception: %s' % e)
self.SvcStop()
# 延时再检查
win32api.Sleep(600000, True)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
nowtime = datetime.now().strftime("%Y.%m.%d %H:%M:%S.%f")[:-3]
self.log('%s -- stopping' % nowtime)
self.stop()
self.log('%s -- stopped' % nowtime)
win32event.SetEvent(self.hWaitStop)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
if __name__ == "__main__":
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(AutoRunTest)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(AutoRunTest)
代码实现后,还需要注册成服务:
安装服务
# 手动运行服务
python AutoRunTest.py install
# 自动运行服务
python AutoRunTest.py --startup auto install
删除服务
python AutoRunTest.py remove
需要注意的是,服务中调用Dos命令或bat脚本,其默认当前路径是
\Python39\Lib\site-packages\pywin32_system32,如果要运行命令,须切换到对应的路径。