[英]How to timeout when executing command line programs in Python?
我正在從Python執行Maple,如果超出最大時間,我想停止該程序。 如果它是Python函數,則可以使用超時裝飾器來完成。 但是我不確定如何進行命令行調用。 這是偽代碼
import os
import timeit as tt
t1 = tt.default_timer()
os.system('echo path_to_maple params')
t2 = tt.default_timer()
dt = t2 - t1
只是為了計時此程序,一切正常。 但是,楓樹程序要花很多時間,所以我想定義一個maxtime,檢查t1 <maxtime是否讓程序執行,否則。 即將腳本更改為以下內容:
import sys
maxtime = 10 # seconds
t1 = tt.default_timer()
if (t1 < maxtime):
os.system('echo path_to_maple params')
t2 = tt.default_timer()
dt = t2 - t1
else:
sys.exit('Timeout')
目前,這不起作用。 有一個更好的方法嗎?
您可以使用subprocess.Popen
生成子進程。 確保正確處理stdout和stderr。 然后使用Popen.wait(timeout)
調用,並在TimeoutExpired
到達時Popen.wait(timeout)
進程。
使用subprocess.Popen()
進行出價,如果您使用的是3.3之前的Python版本,則必須自己處理超時,例如:
import subprocess
import sys
import time
# multi-platform precision clock
get_timer = time.clock if sys.platform == "win32" else time.time
timeout = 10 # in seconds
# don't forget to set STDIN/STDERR handling if you need them...
process = subprocess.Popen(["maple", "args", "and", "such"])
current_time = get_timer()
while get_timer() < current_time + timeout and process.poll() is None:
time.sleep(0.5) # wait half a second, you can adjust the precision
if process.poll() is None: # timeout expired, if it's still running...
process.terminate() # TERMINATE IT! :D
在Python 3.3+中,它就像調用一樣簡單:subprocess.run subprocess.run(["maple", "args", "and", "such"], timeout=10)
我想你可以用
threading.Timer(TIME, function , args=(,))
延遲后執行功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.