下面的代码旨在处理错误,并不断尝试直至成功。很少会抛出FileNotFound错误(我可以在控制台中看到它们),但是在这些情况下,它似乎没有再尝试,因为错误触发后我没有得到新的镜像。
saved = False
while not saved:
saved = True
try:
os.rename(imagePath, savePath)
except FileNotFoundError:
saved = False
最佳答案
我敢说几乎不是while
的Python中的每个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重试修饰符”。