异常处理 - 睡眠然后重试产生错误的同一行

时间:2018-04-18 20:48:39

标签: python loops exception-handling sleep

假设我每次运行时都会在脚本的不同行引发异常(不可预测/不一致)。如何以这样的方式处理此异常:(1)强制脚本在错误之后休眠几秒钟然后(2)尝试重新执行导致错误的相同代码行,以期获得成功结果第二次(或第三次,或第四次......),AND(3)不会重新执行脚本中导致该点的所有行?换句话说,我希望它“转到”前一行并再试一次,直到成功为止,尽管试图避免无限循环的次数上限。

以下代码是我的问题的概念示例。打印出所需的结果:

一个 乙 C d ë

但是打印出类似的内容:

一个 一个 乙 一个 乙 一个 一个 一个 一个 乙 一个 一个 一个 乙 C d ë

import time, random

success, attempts = False, 0

while success == False and attempts <= 20:
    try:

        x, y = 1, random.choice([0,1])
        x/y
        print "A"

        x, y = 1, random.choice([0,1])
        x/y
        print "B"

        x, y = 1, random.choice([0,1])
        x/y
        print "C"

        x, y = 1, random.choice([0,1])
        x/y
        print "D"

        x, y = 1, random.choice([0,1])
        x/y
        print "E"

        success = True
    except ZeroDivisionError:
        attempts += 1
        time.sleep(3)

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用条件和明确跟踪的待办事项列表伪造一组goto。每次任务成功时,将其从待办事项列表中删除,以便您不会再次尝试。

import time, random

attempts = 0
# Reverse order because it's more efficient to remove an item
# from the end of a list than the beginning. Use a deque
# if this bothers you.
to_do = ["E", "D", "C", "B", "A"]
while to_do and attempts <= 20:
    try:
        if to_do[-1] == "A":
            x, y = 1, random.choice([0,1])
            x/y
            print "A"
            to_do.pop()
        elif to_do[-1] == "B": 
            x, y = 1, random.choice([0,1])
            x/y
            print "B"
            to_do.pop()
        elif to_do[-1] == "C":
            x, y = 1, random.choice([0,1])
            x/y
            print "C"
            to_do.pop()
        elif to_do[-1] == "D":
            x, y = 1, random.choice([0,1])
            x/y
            print "D"
            to_do.pop()
        elif to_do[-1] == "E":
            x, y = 1, random.choice([0,1])
            x/y
            print "E"
            to_do.pop()
    except ZeroDivisionError:
        attempts += 1
        time.sleep(3)

但是,通过为每个任务定义一个单独的函数,并使用函数本身的存在,可以显着清除它 在failures列表中,表明仍然需要运行。

to_do = [task_e, task_d, task_c, task_b, task_a]
while attempts <= 20:
    while to_do:
        try:
            to_do[-1]()
        except ZeroDivisionError:
            attempts += 1
            time.sleep(3)
        else:
            to_do.pop()