持续自动化测试之Windows服务

    持续集成除了第三方工具,还有计划任务,当然,也可以通过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,如果要运行命令,须切换到对应的路径。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zljun8210

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值