[英]Retry for-loop in Python
這是我的代碼示例:
from time import sleep
for i in range(0,20):
print(i)
if i == 5:
sleep(2)
print('SomeThing Failed ....')
輸出為:
1
2
3
4
5
SomeThing Failed ....
6
7
8
9
但是我希望出現“失敗”時,再次重試並繼續,如下所示:
1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9
只需將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)
輸出
0
1
2
3
4
5
SomeThing Failed ....
5
6
7
8
9
您可以在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
取決於任務,例如您可能需要try-except
:
for i in range(20):
while True:
try:
do_stuff() # raises exception
except StuffError:
continue
break # no exception was raised, leave loop
如果要限制嘗試次數,則可以嵌套另一個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)
每次迭代僅重試一次
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
輸出為: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.