requests - python retrying github
How to retry after exception? (10)
I have a loop starting with
for i in range(0, 100). Normally it runs correctly, but sometimes it fails due to network conditions. Currently I have it set so that on failure, it will
continue in the except clause (continue on to the next number for
Is it possible for me to reassign the same number to
i and run through the failed iteration of the loop again?
A generic solution with a timeout:
import time def onerror_retry(exception, callback, timeout=2, timedelta=.1): end_time = time.time() + timeout while True: try: yield callback() break except exception: if time.time() > end_time: raise elif timedelta > 0: time.sleep(timedelta)
for retry in onerror_retry(SomeSpecificException, do_stuff): retry()
while True inside your for loop, put your
try code inside, and break from that
while loop only when your code succeeds.
for i in range(0,100): while True: try: # do stuff except SomeSpecificException: continue break
Here's my idea on how to fix this:
j = 19 def calc(y): global j try: j = j + 8 - y x = int(y/j) # this will eventually raise DIV/0 when j=0 print("i = ", str(y), " j = ", str(j), " x = ", str(x)) except: j = j + 1 # when the exception happens, increment "j" and retry calc(y) for i in range(50): calc(i)
I prefer to limit the number of retries, so that if there's a problem with that specific item you will eventually continue onto the next one, thus:
for i in range(100): for attempt in range(10): try: # do thing except: # perhaps reconnect, etc. else: break else: # we failed all the attempts - deal with the consequences.
The retrying package is a nice way to retry a block of code on failure.
@retry(wait_random_min=1000, wait_random_max=2000) def wait_random_1_to_2_s(): print "Randomly wait 1 to 2 seconds between retries"
The clearest way would be to explicitly set
i. For example:
i = 0 while i < 100: i += 1 try: # do stuff except MyException: continue
There is something similar in the Python Decorator Library.
Please bear in mind that it does not test for exceptions, but the return value. It retries until the decorated function returns True.
A slightly modified version should do the trick.
for i in range(100): def do(): try: ## Network related scripts except SpecificException as ex: do() do() ## invoke do() whenever required inside this loop
You can use Python retrying package. Retrying
It is written in Python to simplify the task of adding retry behavior to just about anything.
increment your loop variable only when the try clause succeeds