我有一个python脚本,其中有一个命令要执行,例如:
sample_command_that_may_fail()假设上面的命令由于网络问题而失败,如果它只在执行命令2-3次之后才成功。
在python中是否有重新尝试它的内置函数,或者任何可用的链接或提示?我在python中非常新手,因为指向这个的任何链接都会对我有帮助。
发布于 2014-12-09 06:39:08
您可以考虑重试模块。
示例:
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()发布于 2014-12-09 06:39:27
因为您没有给出任何细节,所以很难有更多的,嗯,具体的,但是通常您可以只使用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')这个尝试了3次my_command()。它对my_command()的行为做了一些假设。
NetworkError;请注意避免使用口袋妖怪例外。None。https://stackoverflow.com/questions/27372782
复制相似问题