Last active
December 5, 2019 16:40
-
-
Save curtis1000/7511c20712321822184b80112fd885e3 to your computer and use it in GitHub Desktop.
Python Retries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
# testing out the retry pattern described here: | |
# https://stackoverflow.com/questions/2083987/how-to-retry-after-exception/2083996#2083996 | |
tries = 5 | |
sleep = 1 | |
########################################## | |
print("\nTest case: complete failure\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
raise Exception | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') | |
########################################## | |
print("\nTest case: works on first try\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') | |
########################################## | |
print("\nTest case: eventually works\n") | |
for attempt in range(tries): | |
try: | |
print(f'Trying {attempt}...') | |
if attempt < 2: | |
raise Exception | |
except: | |
print('Failure, sleeping...') | |
time.sleep(sleep) | |
else: | |
print('Success, moving on!') | |
break | |
else: | |
print(f'We failed all {tries} tries') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment