Skip to content

Instantly share code, notes, and snippets.

@m-ocean-it
Last active February 28, 2022 16:04
Show Gist options
  • Save m-ocean-it/31b13b44c641a7572b2ecf9a71ee5b97 to your computer and use it in GitHub Desktop.
Save m-ocean-it/31b13b44c641a7572b2ecf9a71ee5b97 to your computer and use it in GitHub Desktop.
Function for running some task until no exception arises
from time import sleep
def try_until_success(task,
delay=0,
number_of_tries=3,
exception_to_catch=Exception):
success = False
tries = 0
while not success and tries < number_of_tries:
try:
print('Attempting execution...')
tries += 1
task()
except exception_to_catch:
print(
f'Failed (try #{tries}). Trying again in {delay} seconds...')
sleep(delay)
continue
success = True
if success:
print(f'Success! ({tries} attempts)')
else:
print(f'Failed. ({tries} attempts)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment