首页 > 编程语言 >解决python自动化操作异常处理的问题

解决python自动化操作异常处理的问题

时间:2024-07-31 23:52:53浏览次数:13  
标签:自动化 return python args onFail kwargs print new 异常

在python自动化领域,往往要用到pyautogui,pywin32等模块实现自动化操作。然而,这种自动化操作,本身具有一定的局限性,其中最主要的一个问题就是,一旦执行结果不按照脚本预设的来执行,往往会抛出异常,导致程序中断。

解决这个问题,主要有这么几种思路:

第一,每一次操作后分情况讨论。这种方法的弊端是代码过于冗长,不够直观。

第二,对异常进行处理,例如重启函数。但是这里遇到一个问题,重启次数是多少,怎么避免循环,如何根据异常类型实时修改重启函数的参数,对异常的后处理操作后如何再次重启回归正轨等等。要解决这些问题,代码逻辑复杂。

基于这个原因,本文实现通过装饰器,实现了对函数的封装。主要有以下几个功能:

1、指定重启函数的次数。

2、限定重启函数的重启时间。

3、可以指定异常处理函数,在抛出异常后,执行处理函数,然后再次尝试重启。

4、可以根据函数重启的次数,传入不同的参数值。

其代码如下:

(1)修饰器部分:

def retryOnException(maxAttempts=3, delay=1, exceptions=(Exception,), timeout=None, onFail=None, paramModifier=incrementParam):
    def decorator(func):
        def wrapper(*args, **kwargs):
            startTime = time.time()
            attempts = 0
            while attempts < maxAttempts:
                if paramModifier:
                    new_args, new_kwargs, args, kwargs = paramModifier(*args, **kwargs)
                try:
                    return func(*new_args, **new_kwargs)
                except exceptions as e:
                    print("An exception occured:{}".format(e))
                    print("Attempting to retry... Attempt {}/{}".format(attempts+1, maxAttempts))
                    time.sleep(delay)
                    attempts += 1
                    if timeout and time.time() - startTime > timeout:
                        if onFail:
                            result =  onFail(*args, **kwargs)
                            if result is not None: #表明问题已经修复了
                                attempts = 0 #重置尝试次数
                                continue
                            else:
                                #表明问题没有修复,执行没有结果
                                raise RuntimeError(
                                    "Function {} failed after {} onFail.".format(func.__name__, maxAttempts))
                        else:
                            raise TimeoutError("Function {} time out after {} seconds.".format(func.__name__, timeout))
            if onFail:
                result = onFail(*args, **kwargs)
                if result is not None:  # 表明问题已经修复了
                    return wrapper(*args, **kwargs)
                else:
                    # 表明问题没有修复,执行没有结果
                    raise RuntimeError(
                        "Function {} failed after {} onFail.".format(func.__name__, maxAttempts))
            else:
                raise RuntimeError("Function {} failed after {} attempts.".format(func.__name__, maxAttempts))
        return wrapper
    return decorator

(2)参数选择器

def incrementParam(*args, **kwargs):
    if "increment" in kwargs:
        index = kwargs["increment"]
        kwargs["increment"] += 1
        new_args, new_kwargs = kwargs["argsList"][index] #{"increment":0, "argsList":[([],{}),]}
        return new_args, new_kwargs, args, kwargs
    else:
        return args, kwargs, args, kwargs

(3)异常处理函数和主程序代码

def hello(*args, **kwargs):
    print("处理异常情况部分")
    return None

@retryOnException(maxAttempts=3, delay=2, timeout=10, onFail=hello)
def testFunction(a, b, c, good):
    print("trying to excute function...")
    print(a, b, c, good)
    import random
    if random.randint(0, 0) == 0:
        raise ValueError("someting went wrong!")
    return "Function executed successfully"

try:
    print(testFunction(increment = 0, argsList = [([1,2,3,4], {}), ([2,2,2,1],{}), ([3,4,3], {"good":3})]))
except(RuntimeError, TimeoutError) as e:
    print("================")
    print(str(e))

try:
    print( testFunction(1, 2, "yes", good="yes") )
except Exception as e:
    print("huhuu")
pass

以上代码非常简洁,可以完美实现对函数异常的重启处理,并且具有一定的异常修复功能。例如:在微信自动化程序项目中,由于交互问题导致的偶发性发送信息或者文件失败,可以通过该方法实现异常判别并自动处理,具有比较好的代码稳定性。

标签:自动化,return,python,args,onFail,kwargs,print,new,异常
From: https://blog.csdn.net/nh111/article/details/140783867

相关文章

  • Python爬虫入门03:用Urllib假装我们是浏览器
    文章目录引言Urllib库简介Request模块详解Error模块与异常处理Parse模块与URL解析Robotparser模块模拟浏览器请求使用Request方法添加请求头信息代码示例1.设置请求URL和请求头2.定义请求参数并转换为适当的格式3.使用Request方法封装请求4.发送请求并获取响应常用......
  • Java内存区域与内存溢出异常 - 运行时数据区
    一、运行时数据区1.1程序计数器-线程私有可以看做当前线程所执行的字节码行号指示器,在任意时刻一个处理器(对于多核处理器来说是一个内核)都只会执行一条线程中的指令。所以为了线程切换后能恢复到正确的执行位置,每条线程都需要有一个独立的线程计数器,各条线程之间计数器互不......
  • 请以零基础学Python 之 第二十讲 分组和贪婪匹配
    当我们处理字符串时,有时候需要根据特定的模式来分割或者提取信息。Python提供了强大的正则表达式库re,可以帮助我们实现这些复杂的字符串操作。本篇博客将介绍两个常用的正则表达式技巧:分组和贪婪匹配。分组(Grouping)在正则表达式中,分组是将多个模式单元组合为一个单元,以便......
  • 零基础学python 之 第十九讲 正则表达式
    当你开始学习Python编程时,正则表达式是一项非常强大的工具,用于处理文本数据中的模式匹配和搜索。本篇博客将带你从零开始学习如何在Python中使用正则表达式。1.什么是正则表达式?正则表达式(RegularExpression)是用于描述字符串模式的一种工具,可以用来匹配、查找、替换符合特......
  • python之贪吃蛇
    废话不多说,直接上代码(确保已经安装pygame)importpygameimportrandom#基础设置#屏幕高度SCREEN_HEIGHT=480#屏幕宽度SCREEN_WIDTH=600#小方格大小GRID_SIZE=20#颜色设置WHITE=(255,255,255)BLACK=(0,0,0)GREEN=(0,255,0)#初始化Pyg......
  • Python - Context Managers
    withstatementHereisthesyntaxofthewithstatement:withexpressionasvar:statementsTheexpressionshouldbeacontextmanagerobject,oritshouldproduceacontextmanagerobject.Whenthiswithstatementisexecuted,thefirstthingthat......
  • python装饰器
    一前言环境:win10python3.10二函数中的函数如果定义了一个函数A,现在想在不影响函数A原先功能的情况下,新增加一些额外的功能,怎么办,下面是一个例子如上,本来原先执行test_except那句话只会打印over那句话,但现在执行test_except却会输出一些另外的东西这其中有个巧妙地东西就......
  • 异常概述及其抛出与捕获机制
    文章目录一、异常概述1.1什么是异常1.2引入异常的好处1.3异常处理流程1.4异常处理机制的要求二、异常类型2.1异常类别2.2Exception类的层次三、抛出异常3.1throws关键字3.2throw关键字3.3链式异常3.4throw和throws的区别四、捕获异常(异常处理程序)4.1......
  • Python - Built-in Exceptions: Python Exceptions Class Hierarchy
     Figure20.4:Built-inexceptionsTheclassBaseExceptionisthebaseclassofallthebuilt-inexceptionclasses.FromBaseException,fourclassesnamedException,SystemExit,KeyboardInterruptandGeneratorExitarederived.Alltheremainingbuilt-in......
  • Python - Strategies to handle exceptions in your code
    Therearetwoapproachesthatcanbefollowedwhenwewanttodealwithexceptionsthatoccurduetounusualevents:LBYL-LookBeforeYouLeapEAFP-EasiertoAskforForgivenessthanPermissionIntheLBYLapproach,weavoidexceptions,whileinthe......