---
title: "python黑魔法异常重试的次数，间隔的装饰器涵数"
author: "ronin47"
date: "2017-11-23T14:50:47Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2017-11-23T14:55:31Z"
id: 2400618
url: "https://hugoren.iteye.com/blog/2400618"
---

```
起因：
   在github找到一个库retrying
   但这个库一点也不好用，好久没维护了
   索性，造一个
   还可以扩展timeout
from functools import wraps
from threading import Event


def retry_exception(retry_count=0, interval_wait=0):
    def wrap(f):
        @wraps(f)
        def func(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except Exception as e:
                if retry_count == 0:
                    return str(e)
                if retry_count >= 1:
                    count = retry_count
                    while 1:
                        Event().wait(interval_wait)
                        try:
                            count = count - 1
                            return f(*args, **kwargs)
                        except Exception as e:
                            if count == 0:
                                return str(e)
                            continue
        return func
    return wrap


@retry_exception(retry_count=3, interval_wait=3)
def tt():
    a = 1
    if a != 2:
        raise Exception('i am exception')
    print(a)

```

print(tt())