对异常函数进行重试数次

2015-10-17 0 916
对异常函数进行重试数次
def retry(times=1,exceptions=None):
    exceptions = exceptions if exceptions is not None else Exception
    def wrapper(func):
        def wrapper(*args,**kwargs):
            last_exception =None
            for _ in range(times):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
            raise last_exception
        return wrapper
    return wrapper

if __name__=="__main__":
    @retry(5)
    def test():
        print("do something")
        raise Exception
    test()

遇见资源网 python 对异常函数进行重试数次 http://www.ox520.com/15852.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务