I want to use a subprocess to run the program, but I need to limit the execution time. For example, if it lasts more than 2 seconds, I want to kill him.
For regular programs, kill () works well. But if I try to run /usr/bin/time something , kill () cannot really kill the program.
But my code below does not look very good, the program is still working.
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()
python subprocess kill
Xhacker liu
source share