使用子进程时如何限制程序的执行时间? [英] How to limit program's execution time when using subprocess?
问题描述
我想使用子流程来运行程序,并且需要限制执行时间.例如,如果它运行超过2秒,我想杀死它.
I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds.
对于常见程序,kill()效果很好.但是,如果我尝试运行/usr/bin/time something
,kill()并不能真正终止程序.
For common programs, kill() works well. But if I try to run /usr/bin/time something
, kill() can’t really kill the program.
我下面的代码似乎无法正常工作.该程序仍在运行.
My code below seems doesn’t work well. The program is still running.
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()
推荐答案
在命令行中执行以下操作:
do it like so in your command line:
perl -e 'alarm shift @ARGV; exec @ARGV' <timeout> <your_command>
这将运行命令<your_command>
并在<timeout>
秒内终止它.
this will run the command <your_command>
and terminate it in <timeout>
second.
一个虚拟的例子:
# 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一起使用,但它是相同的.
or you can use the signal.alarm() if you want it with python but it's the same.
这篇关于使用子进程时如何限制程序的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!