python – How to retry after exception?

python – How to retry after exception?

Do a 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

I prefer to limit the number of retries, so that if theres 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.

python – How to retry after exception?

UPDATE 2021-12-01:

As of June 2016, the retrying package is no longer being maintained.
Consider using the active fork github.com/jd/tenacity, or alternatively github.com/litl/backoff.


The retrying package is a nice way to retry a block of code on failure.

For example:

@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)

Leave a Reply

Your email address will not be published. Required fields are marked *