栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

持续自动化测试之Windows服务

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

持续自动化测试之Windows服务

    持续集成除了第三方工具,还有计划任务,当然,也可以通过Windows服务来实现。

    通过Python实现Windows服务,需要三方库win32,可以通过pip安装:pip install win32。

注意,安装完win32后,需要把两个路径加到系统路径,不然服务运行会出问题:

  1、 Python39Libsite-packagespywin32_system32

  2、 Python39Libsite-packageswin32

    

 

    下面就上代码:

# -*- 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脚本,其默认当前路径是

    Python39Libsite-packagespywin32_system32,如果要运行命令,须切换到对应的路径。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/303627.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号