while loop exit after receive error in a try except

76 views Asked by At

I would like to execute the Python code, but in the event of a timeout error, I want the code to automatically retry after a 60-second delay and continue. However, if another error occurs, such as a permission issue, the code should exit with the corresponding error message. The current code I have below doesn't exit properly and gets stuck in an infinite loop. How can I modify the code to address this issue? Please advise

 pause=60
 while True:
   try:
     df=report.next_records()   ##call the function here
   except:
     sleep(pause)
     pause+=60
   else:
     break  



  
2

There are 2 answers

5
TimbowSix On

Catch the specific Exception

pause=60
while True:
    try:
        df=report.next_records()   ##call the function here
    except TimeoutError: # or whatever error you're catching
        sleep(pause)
        pause+=60
1
Mohammed almalki On

i think this will help :


import traceback


pause=60

while True:
    try:
        df=report.next_records()
    except:
        print(traceback.format_exc())
        sleep(pause)


# and you can add a condition to stop it when some thing happens


import traceback


pause=60

continue_doing = True

while continue_doing:
    try:
        df=report.next_records()

        if df:                          # here put for example your condition
            continue_doing = False

    except:
        print(traceback.format_exc())
        sleep(pause)
        # pause+=60 i think you do not need this because you want to wait the same time as 60s.