schedule task if exception has occurred python

Question:

my question is simple as the title suggest

try:
    response = requests.get(URL2)  # download the data behind the URL
    open(zipname, "wb").write(response.content)  # Open the response into a new file
    # extract zip file to specified location
    with ZipFile(zipname, 'r') as zip_file:
        zip_file.extractall(path=path)
    os.remove(zipname)  # removes the downloaded zip file
    print("itworks")
except (requests.exceptions.ConnectionError, FileNotFoundError):
    print("finally the error")
    #  retry the try part after some seconds

now i want it to retry and go over again in case the exception happen, after some time.

Asked By: siddhant gulia

||

Answers:

If I understand correctly you can do the following:

from time import sleep

no_of_attempts = 5 # set number of attempts
for i in range (no_of_attempts):
    try:
        response = requests.get(URL2)  # download the data behind the URL
        open(zipname, "wb").write(response.content)  # Open the response into a new file
        # extract zip file to specified location
        with ZipFile(zipname, 'r') as zip_file:
            zip_file.extractall(path=path)
        os.remove(zipname)  # removes the downloaded zip file
        print("itworks")
        break
    except (requests.exceptions.ConnectionError, FileNotFoundError):
        print("finally the error")
        sleep(3)
        continue

This way you can retry the "try" part as many times as you set no_of_attempts to be.

You could also set while True if you want it to try until is succeeds and then break inside the try but I would not recommend it

Answered By: Ofek Glick

You can always make it a recursive function and import time module to wait x seconds.

For instance:

import time

def doSomething():
    try:
        response = requests.get(URL2)  # download the data behind the URL
        open(zipname, "wb").write(response.content)  # Open the response into a new file
        # extract zip file to specified location
        with ZipFile(zipname, 'r') as zip_file:
            zip_file.extractall(path=path)
        os.remove(zipname)  # removes the downloaded zip file
        print("itworks")
    except (requests.exceptions.ConnectionError, FileNotFoundError):
        print("finally the error")
        #  retry the try part after some seconds
        time.sleep(1000)
        # Try again
        doSomething()
Answered By: IMB

FOA (Looking at the accepted answer) I wouldn’t use recursion where it’s not necessary for a whole bunch of reasons, among which readability, mantainability, and the very name of this platform.

Then I would exempt doSomething() from catching the exception and embed the try-catch block in a while loop, like so:

def doSomething():
    "do something here"

while True:
    try:
        doSomething()
        print("success")
        break
    except (requests.exceptions.ConnectionError, FileNotFoundError):
        print("error, trying again in 10s")
        time.sleep(10)
        

This does a better job at separating concerns; doSomething() just has to… do something. Error catching/logging can be handled outside.

Answered By: Max Shouman