deathwing_destroyer
deathwing_destroyer

Reputation: 19

Python error handling not working as intended

The below code is meant to handle an error and keep trying until it succeeds. Very rarely a FileNotFound error will be thrown (I can see them in console) but in these cases it doesn't seem to be trying again, as I do not get a new image when the error trips.

saved = False
while not saved:
        saved = True
        try:
            os.rename(imagePath, savePath)
        except FileNotFoundError:
            saved = False

Upvotes: 0

Views: 51

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77339

I dare to say almost every while loop in Python that is not while True is a code smell. This is untested but should nudge you in the right direction:

max_retries = 10
retry_time = 0.1
retries = 10

while True:
    retries += 1
    try:
         os.rename(image_path, save_path)
    except FileNotFoundError:
         time.sleep(retry_time)  # lets avoid CPU spikes
    else:
         break  # Everything OK, lets move on
    if retries > max_retries:
         # We don't want to get stuck if for some reason the file
         # is deleted before we move it or if it never arrives.
         msg = f"Failed to move {image_path} to {save_path} after {retries} times."
         raise Exception(msg)  # or log the event and break the loop

There are several options of "retry" decorators for Python, try to google "python retry decorator".

Upvotes: 1

Related Questions