python 将装饰器改成用语句,使用与语句实现错误重试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 将装饰器改成用语句,使用与语句实现错误重试相关的知识,希望对你有一定的参考价值。

# -*- coding: utf-8 -*-
from contextlib import contextmanager

@contextmanager
def retrys(max_tries=4):
    import codecs
    import re
    import time
    import math
    import traceback
    from inspect import getouterframes, currentframe, getmembers
    index = list(map(lambda item: item[-2][0].strip().startswith('with'), getouterframes(currentframe()))).index(True)

    (frame, filename, line_number,
     function_name, lines, index) = getouterframes(currentframe())[index]
    member = getmembers(frame)
    f_locals_index = ['f_locals' in i for i in member].index(True)
    f_globals_index = ['f_globals' in i for i in member].index(True)
    params = {}
    params.update(member[f_locals_index][-1])
    params.update(member[f_globals_index][-1])
    # 仅仅适用于python2
    for key, value in params.items():
        exec ('{}=value'.format(key))
    try:
        yield
    except:
        time.sleep(1)
        for i in range(1, max_tries):
            with codecs.open(filename, 'r', 'utf-8') as f:
                text = f.readlines()
                flag = re.findall('^\s+', ' ' + text[line_number])[0].__len__()
                content = ''
                for line in text[line_number:]:
                    blank = re.findall('^\s+', ' ' + line)[0].__len__()
                    if blank < flag:
                        break
                    content += line[flag - 1:]
            try:
                exec (content)
            except:
                print('================================================')
                traceback.print_exc()
                if i != max_tries - 1:
                    time.sleep(math.pow(2, i))
import random
from tt import retrys


def g():
    pass


class A():
    def __init__(self):
        self.a = 0
        self.b = 2

    @classmethod
    def e(cls):
        pass

    @staticmethod
    def f():
        pass

    def c(self, d):
        with retrys():
            if random.random() > 0.5:
                raise Exception('dd')
            print('success', self, d, self.e, self.f, g)


b = A()
b.c(2)

以上是关于python 将装饰器改成用语句,使用与语句实现错误重试的主要内容,如果未能解决你的问题,请参考以下文章

python(描述符应用与类的装饰器)

Python函数进阶:闭包装饰器生成器协程

Python小脚本基于装饰器的函数日志脚本

Python小脚本基于装饰器的函数日志脚本

Python函数与装饰器入门一

python闭包和装饰器