Skip to content

Instantly share code, notes, and snippets.

@curtis1000
Last active December 5, 2019 16:40
Show Gist options
  • Save curtis1000/7511c20712321822184b80112fd885e3 to your computer and use it in GitHub Desktop.
Save curtis1000/7511c20712321822184b80112fd885e3 to your computer and use it in GitHub Desktop.
Python Retries
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