我想使用子进程来运行程序,我需要限制执行时间。例如,如果它运行超过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()
最佳答案
在命令行中这样做:
perl -e 'alarm shift @ARGV; exec @ARGV' <timeout> <your_command>
这将运行命令
<your_command>
并在 <timeout>
秒内终止它。一个虚拟的例子:
# set time out to 5, so that the command will be killed after 5 second
command = ['perl', '-e', "'alarm shift @ARGV; exec @ARGV'", "5"]
command += ["ping", "www.google.com"]
exec_proc = subprocess.Popen(command)
或者你可以使用 signal.alarm () 如果你想要它与 python 但它是一样的。
关于python - 使用子进程时如何限制程序的执行时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4033578/