1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import functools import time
def retry(interval, max_retries=3, exceptions=None): if exceptions is None: exceptions = Exception
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(max_retries): try: res = func(*args, **kwargs) return res except exceptions: time.sleep(interval) pass res = func(*args, **kwargs) return res
return wrapper
return decorator
def retry(max_retries=3, exceptions=None, interval=0): if exceptions is None: exceptions = Exception
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(max_retries): try: return func(*args, **kwargs) except exceptions: time.sleep(interval) return func(*args, **kwargs)
return wrapper
return decorator
i = 0
@retry(interval=0.5) def my_func(): global i i += 1 print(i) raise Exception
def main(): my_func()
if __name__ == '__main__': main()
|