Inspired by: https://wiki.python.org/moin/PythonDecoratorLibrary#Retry
# Parmeters
Exceptions:
description: Exception(s) to check. May be a tuple of exceptions to check.
example: IOError or IOError(errno.ECOMM) or (IOError,) or (ValueError, IOError(errno.ECOMM)
type: Exception type, exception instance, or tuple containing any number of both
Tries:
description: Number of times to try (not retry) before giving up.
example: 3
type: integer
Delay:
description: Initial delay between retries in seconds.
example: 3
type: integer
Backoff:
description: Backoff multiplier
example: Value of 2 will double the delay each retry
type: integer
Silent:
description: If set then no logging will be attempted.
example: True
type: Boolean
Logger:
description: Logger to use. If None, print.
example: log = getLogger(__name__)
type: logging.Logger
fromloggingimportbasicConfig, getLogger, INFOfromretryimportretrybasicConfig(level=INFO)
log=getLogger(__name__)
@retry((TestError, IOError), tries=6, delay=1, backoff=2, silent=False, logger=log)defyourfunction(self, example):
try:
...
except:
raiseTestErrorfinally:
log.INFO('No Errors!')fromretryimportretry@retry(Exception, tries=4)deftest_fail(text):
raiseException('Fail')
test_fail('It Works!')fromretryimportretry@retry(Exception, tries=4)deftest_success(text):
print('Success: {0}'.format(text))
test_success('It Works!')fromretryimportretryfromrandomimportrandom@retry(Exception, tries=4)deftest_random(text):
x=random()
ifx<0.5:
raiseException('Fail')
else:
print('Success: {0}'.format(text))
test_random('It Works!')fromretryimportretryfromrandomimportrandom@retry((NameError, IOError), tries=20, delay=1, backoff=1)deftest_multiple_exceptions():
x=random()
ifx<0.40:
raiseNameError('NameError')
elifx<0.80:
raiseIOError('IOError')
else:
raiseKeyError('KeyError')
test_multiple_exceptions()