from functools import wraps
import time
def retry_decorator(retry_num: int, sleep_sec: int):
"""
Returns the decorator to retry
:param retry_num:number of retries
:param sleep_sec:Number of seconds to sleep before retrying
:return:Decorator
"""
def _retry(func):
@wraps(func)
def wrapper(*args, **kwargs):
for retry_count in range(1, retry_num + 1):
try:
ret = func(*args, **kwargs)
return ret
except Exception as exp: # pylint: disable=broad-except
if retry_count == retry_num:
print(f"Retry_count over ({retry_count}/{retry_num})")
raise Exception from exp
else:
print(f"Retry after {sleep_sec} sec ({retry_count}/{retry_num}). Error = {exp}")
time.sleep(sleep_sec)
return wrapper
return _retry
@retry_decorator(retry_num=3, sleep_sec=1)
def hoge():
raise Exception("fail")
if __name__ == "__main__":
hoge()
Execution result
Retry after 1 sec (1/3). Error = fail
Retry after 1 sec (2/3). Error = fail
Retry_count over (3/3)
Traceback (most recent call last):
File "retry.py", line 18, in wrapper
ret = func(*args, **kwargs)
File "retry.py", line 35, in hoge
raise Exception("fail")
Exception: fail
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "retry.py", line 39, in <module>
hoge()
File "retry.py", line 23, in wrapper
raise Exception from exp
Exception
Recommended Posts