如果异常重试 Python

If exception retry in Python

我怎么可能去做这样的事情

  1. 尝试做点什么。
  2. 如果有效,很好,继续正常流程。
  3. 如果失败运行一个函数然后重试。
  4. 如果再次失败抛出异常并停止代码。

我相信我必须使用 try,但我还没有完全理解如何在这个特定示例中使用它。

尝试嵌套 try catch:

try:
    do_something() #if this works, will skip rest and continue
except:
    do_fix_function() #on error, do extra function
    try:
        do_something() #try again
    except:
        throw error() #if it fails this time, stop and throw an error

请注意,如果您的 do_fix_function() 也可能失败,您可能希望将其放在第二个 try 语句中

这适用于任意次数的尝试;我把它设置为两个,因为这就是你想要的。

tries = 2
while True:
    try:
        step1()
    except CatchThisException:
        tries -= 1
        if tries:  # if tries != 0
            step3()
            continue  # not necessary, just for clarity
        else:
            raise  # step 4
    else:
        break  # step 2

听起来您根本不想进行嵌套的 try-catch。 Exceptions as control flow are a gnarly anti-pattern,在可以避免的地方,应该

在这种情况下,很容易避免。在您描述的方法中,您希望在对文件执行某些操作之前确保该文件存在。你也有一个方法 "correct" 路径不应该。如果两次尝试都失败了,那么你想摆脱困境。

考虑到这一点,我们希望为此使用 os.path.isfile

from os.path import isfile

def something(filepath):
    # Don't mutate the parameter if you can help it.
    p = filepath
    if not isfile(p):
        p = correct_path(p)
        if not isfile(p):
            raise Error("Cannot find file {} after correction to {}, aborting.".format(filepath, p))
    with open(p, 'r') as f:
        # Rest of file operations here

您可以使用retrying package来解决您的重试问题。只需编写一个不断重复失败的代码块,直到达到最大重试次数

例如:

随机导入 从重试导入重试

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print do_something_unreliable()