[英]Python - Re-run subprocess call when it fails
我有一個調用子進程(speedtest-cli)的腳本。
該腳本似乎隨機失敗並顯示以下錯誤消息:-
ERROR: timed out
ERROR: 'speedtest-cli --share' failed (exit code 1).
Retrieving speedtest.net configuration... Cannot retrieve speedtest configuration
Traceback (most recent call last):
File "/home/steve/speedtest_dev.py", line 80, in <module>
data[1] = data[1].strip("'") ##Finish date and time
IndexError: list index out of range
據我所知,這里似乎有兩個錯誤:-
a) Speedtest-cli 因超時而失敗
ERROR: timed out
ERROR: 'speedtest-cli --share' failed (exit code 1).
和
b) 由於沒有數據,數據條會像人們預期的那樣失敗。
Traceback (most recent call last):
File "/home/steve/speedtest_dev.py", line 80, in <module>
data[1] = data[1].strip("'") ##Finish date and time
IndexError: list index out of range
如果可能,我想捕獲第一個錯誤並在間隔(60 秒?)后重新運行子進程。
我嘗試創建一個函數:-
def run_speedtest():
outfile = open(dataFile, "w+")
subprocess.call(["/home/steve/speedtest-cli-extras/speedtest-csv", "--share"], stdout=outfile)
outfile.close()
然后使用 try 語句,如:-
try:
run_speedtest()
except:
print("1st attempt failed") #for testing only
time.sleep(60)
run_speedtest()
出於某種原因,我只設法運行了第一部分,當出現錯誤時,except 語句似乎沒有運行。 然后腳本執行以下操作:-
#Separate Values from csv string
with open(dataFile, "r+") as f:
data = f.read()
data = data.strip()
data = data.replace("\t","|")
f.seek(0)
f.write(data)
f.truncate
f.close()
#Open file and process
with open(dataFile, "r") as g:
data = g.read()
data = data.split("|")
寫入數據庫並在其中一個參數小於定義的值時發送電子郵件。
除非初始 run_speedtest() 失敗,否則一切正常。
任何幫助將不勝感激。
升級最近的python版本后我遇到了同樣的問題,解決方案可以是:
導出 PYTHONHTTPSVERIFY=0
蟒蛇你的_腳本
不過它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.