简体   繁体   English

在Python中重试for循环

[英]Retry for-loop in Python

Here is my Code for Example : 这是我的代码示例:

from time import sleep
for i in range(0,20):
    print(i)
    if i == 5:
        sleep(2)
        print('SomeThing Failed ....')

Output is : 输出为:

1
2
3
4
5
SomeThing Failed ....
6
7
8
9

But i want when Failed appear , it Retry it again and continue , like this : 但是我希望出现“失败”时,再次重试并继续,如下所示:

1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9

Just put the working part into a function, and it will retry once by checking the return value 只需将working部件放入函数中,它将通过检查返回值重试一次

from time import sleep

def working(i):
    print(i)
    if i == 5:
        return False
    return True

for i in range(0,10):
    ret = working(i)
    if ret is not True:
        sleep(2)
        print('SomeThing Failed ....')
        working(i)

output 输出

0
1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9

You could do this with a while loop inside the for loop, and only break out of that loop when the thing you attempted succeeded: 您可以在for循环内使用while循环来执行此操作,并且仅在尝试执行的操作成功时才​​退出该循环:

for i in range(20):
    while True:
        result = do_stuff()  # function should return a success state! 
        if result:
             break  # do_stuff() said all is good, leave loop

Depends a little on the task, eg you might want try-except instead: 取决于任务,例如您可能需要try-except

for i in range(20):
    while True:
        try:
            do_stuff()  # raises exception
        except StuffError:
            continue
        break  # no exception was raised, leave loop

If you want to impose a limit on the number of attempts, you could nest another for loop like this: 如果要限制尝试次数,则可以嵌套另一个for循环,如下所示:

for i in range(20):
    for j in range(3):  # only retry a maximum of 3 times
        try:
            do_stuff()
        except StuffError:
            continue
        break
from time import sleep

# Usually you check `i` only once
# which means `countdown` defaults to 1
def check(i, countdown = 1):

    print(i)

    # If `i` is 5 (or any other arbitrary problematic strange number)
    if i == 5:
        sleep(2)

        # Decide if the program should try it again
        # if `countdown` is 0,
        # we stop retrying and continue
        if countdown > 0:
            print('Something Failed ...')

            return check(i, countdown - 1)

# main
for i in range(0, 20):
    check(i)

It retries only one time for each iteration 每次迭代仅重试一次

from time import sleep
i = 0
retry = True
while(i<20):
    print(i)
    if i == 5 and retry:
        retry = False
        sleep(2)
        print('SomeThing Failed ....')
    else:
        i+=1
        retry = True

The output is: 0 1 2 3 4 5 SomeThing Failed .... 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 输出为:0 1 2 3 4 5 SomeThing Failed .... 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM