[英]commands execution in python script
我有一個帶有要執行的命令的python腳本,例如:
sample_command_that_may_fail()
假設上述命令由於網絡問題而失敗,並且僅在執行該命令2-3次后才成功。
我在python中有很多內置的函數可以重試它,或者有可用的鏈接或提示嗎?我是python的新手,因為對此的任何鏈接都對我有幫助。
您可以考慮重試模塊。
例:
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()
由於您沒有提供任何細節,因此很難做到更好,更具體,但是通常您只能使用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
; 注意避免寵物小精靈的異常 。 None
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.