我想使用子进程来运行一个程序,我需要限制执行时间。比如运行超过2秒就想kill掉。
对于普通程序,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()
最佳答案
如果您使用的是 Python 2.6 或更高版本,则可以使用 multiprocessing模块。
from multiprocessing import Process
def f():
# Stuff to run your process here
p = Process(target=f)
p.start()
p.join(timeout)
if p.is_alive():
p.terminate()
实际上,多处理是这个任务的错误模块,因为它只是一种控制线程运行时间的方法。您无法控制线程可能运行的任何子线程。正如奇点所暗示的那样,使用 signal.alarm是正常的做法。
import signal
import subprocess
def handle_alarm(signum, frame):
# If the alarm is triggered, we're still in the exec_proc.communicate()
# call, so use exec_proc.kill() to end the process.
frame.f_locals['self'].kill()
max_time = ...
stdout = stderr = None
signal.signal(signal.SIGALRM, handle_alarm)
exec_proc = subprocess.Popen(['time', 'ping', '-c', '5', 'google.com'],
stdin=None, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
signal.alarm(max_time)
try:
(stdout, stderr) = exec_proc.communicate()
except IOError:
# process was killed due to exceeding the alarm
finally:
signal.alarm(0)
# do stuff with stdout/stderr if they're not None
关于python - 使用子进程时如何限制程序的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4033578/