Home > Back-end >  How to retry in python
How to retry in python

Time:11-08

we know the standard Exception Handling in python:

try:
  print(x)
except:
  print("An exception occurred")

I want to achieve that

  1. if try fails, we will retry again immediately; if try fails second time, we will go to except.
  2. if try fails, we will retry after 1 min; if try fails second time, we will go to except.

Could you offer me some reference of retry function in python?

CodePudding user response:

try the retry decorator from package retry

https://pypi.org/project/retry/

pip install retry

then

from retry import retry

@retry(ZeroDivisionError, tries=3, delay=2)
def make_trouble():
    '''Retry on ZeroDivisionError, raise error after 3 attempts, sleep 2 seconds between attempts.'''
    print(f'trying {1.0/0.0}')



make_trouble()


CodePudding user response:

I haven't heard of any retry function, but you can use loops to achieve almost the same thing

while true:
    try:
        print(x)
        break
    except:
        pass
  • Related