如何在python中进行故障切换?
我想问一下如何在中进行故障切换,如贝娄:如何在python中进行故障切换?,python,Python,我想问一下如何在中进行故障切换,如贝娄: 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() 我想
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函数在我的try中失败,它将从最新的I(不是从1)重新启动它。正如我之前所评论的,您可能希望在try中包装调用..除了,不是定义。这就是你要找的吗
def f():
print "f called: ",
import random
x = random.randint(0, 10) / 8
print "1/x =", 1/x
while True:
try:
f()
break
except ZeroDivisionError:
print "f failed"
continue
或者,如果不想从1重新启动整个函数,为什么不使用try.。函数定义中除外:
def f():
import random
for i in range(1, 10):
while True:
try:
print i,
# do something with i:
print 1 / (i // random.randint(0, 8))
break
except ZeroDivisionError:
continue
f()
您可以使用如下迭代器函数:
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
这里您正在包装
countthis
的定义,但该定义是安全的。请停止使用三种不同的缩进长度。请参阅。但请注意,而True
表示只要错误持续,循环就不会终止-这是您想要的吗?
0
1
2
3
4
5
5 failed
6
7
......
99