Python错误处理无法正常工作

时间:2019-07-31 19:55:24

标签: python error-handling python-os

以下代码旨在处理错误,并不断尝试直至成功。很少会抛出FileNotFound错误(我可以在控制台中看到它们),但是在这些情况下,它似乎没有再尝试,因为错误发生时我没有得到新的映像。

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

1 个答案:

答案 0 :(得分:1)

我敢说Python中几乎不是while的每个while True循环都是代码味道。这未经测试,但应该向正确的方向轻推:

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

Python有“重试”修饰符的几种选择,请尝试使用Google“ python重试修饰符”。