我想使用子進程來運行程序,但我需要限制執行時間。例如,如果它運行超過2秒鐘,我想殺死它。如何在使用子進程時限制程序的執行時間?
對於常見的程序,kill()工作正常。但是,如果我嘗試運行/usr/bin/time something
,kill()不能真正殺死程序。
但我的代碼似乎不太好,程序仍在運行。
import subprocess
import time
exec_proc = subprocess.Popen("/usr/bin/time -f \"%e\\n%M\" ./son > /dev/null", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True)
max_time = 1
cur_time = 0.0
return_code = 0
while cur_time <= max_time:
if exec_proc.poll() != None:
return_code = exec_proc.poll()
break
time.sleep(0.1)
cur_time += 0.1
if cur_time > max_time:
exec_proc.kill()
與http://stackoverflow.com/questions/1191374/subprocess-with-timeout – starrify 2013-10-12 11:48:43