Usually, the program is terminated to prevent exceptions , We will adopt try To get exceptions .
Column such as calling a third party API, Exceptions may occur even if the device status heartbeat is reported and the network is unstable .
We want to automatically repeat the call or specify the number of calls when an exception occurs in the program .
python retrying library , Perfect realization of this requirement .
retrying Provide a decorator function retry, The decorated function will execute again in case of failure , By default, if the error is reported all the time, try again .
Installation Library pip install retrying
from retrying import retry
import time
@retry()
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception
@retry(stop_max_attempt_number=5)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception
@retry(stop_max_delay=5000)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception
@retry(wait_fixed=5000)
def run():
print(' Repeated calls to ')
raise Exception
# Parameters attempts, delay mandatory
def log_error(attempts, delay):
print(' Record exceptions ')
# Specify the exception to call the function repeatedly
@retry(stop_func=log_error)
def run():
print(' Repeated calls to ')
time.sleep(1)
raise Exception
if __name__ == '__main__':
run()