Search code examples
pythonpython-requestsscheduled-taskstry-except

schedule task if exception has occurred python


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.


Solution

  • 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()