我想使用子进程来运行程序,并且需要限制执行时间。例如,如果它运行超过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()
如果您使用的是 Python 2.6 或更高版本,则可以使用多重处理 http://docs.python.org/library/multiprocessing.html module.
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()
实际上,多处理是执行此任务的错误模块,因为它只是控制线程运行时间的一种方法。您无法控制线程可能运行的任何子线程。正如奇点所暗示的那样,使用信号.警报 http://docs.python.org/library/signal.html#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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)