Last active
February 28, 2022 16:04
-
-
Save m-ocean-it/31b13b44c641a7572b2ecf9a71ee5b97 to your computer and use it in GitHub Desktop.
Function for running some task until no exception arises
This file contains hidden or 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
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