我有一个python脚本,其中包含要执行的命令,例如:
sample_command_that_may_fail()
假设上述命令因网络问题而失败,并且仅在执行命令2-3次后才成功。
在python中是否有任何内置函数可以重试它或任何可用的链接或提示?我在python中非常新手,因为任何链接都对我有帮助。
答案 0 :(得分:3)
您可以考虑使用retrying模块。
示例:
import random
from retrying import retry
@retry
def do_something_unreliable():
if random.randint(0, 10) > 1:
raise IOError("Broken sauce, everything is hosed!!!111one")
else:
return "Awesome sauce!"
print do_something_unreliable()
答案 1 :(得分:2)
由于您没有提供任何细节,因此很难更具体,更具体,但通常您只能使用for
循环。示例可能如下所示:
out = None
# Try 3 times
for i in range(3):
try:
out = my_command()
# Catch this specific error, and do nothing (maybe you can also sleep for a few seconds here)
except NetworkError:
pass
# my_command() didn't raise an error, break out of the loop
else:
break
# If it failed 3 times, out will still be None
if out is None:
raise Exception('my_command() failed')
这会尝试my_command()
3次。它对my_command()
:
NetworkError
;注意避免pokemon exceptions。None
以外的内容。