gpt4 book ai didi

python - 如何在Python中进行故障转移?

转载 作者:行者123 更新时间:2023-12-01 05:58:05 25 4
gpt4 key购买 nike

我想问一下如何在 for 中进行故障转移,如下所示:

 again = 1
start = 1
try:
def countthis():
for i in range (start,200):
again = i
print i
except:
print "Failure occured, I will try again"
start = again
countthis.run()

我希望如果 for 函数在 i 的 try 中失败,它会从最新的 i (而不是从 1)重新启动它

最佳答案

您可以使用这样的迭代器函数:

def countthis(start=0, end=100):
for i in range(start, end):
print i
if i == 5:
raise Exception('5 failed')
yield i

然后在出错时使用下一个数字恢复计数器,跳过失败的:

ret = 0
end = 100
while ret < end - 1:
try:
for i in countthis(start=ret, end=end):
ret = i
except Exception, ex:
print ex
# when 5 reached, an exception will be raised, so here we restart at '6'
ret = ret + 2

这最终将打印:

0
1
2
3
4
5
5 failed
6
7
......
99

关于python - 如何在Python中进行故障转移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11598233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com