python - 使用子进程时如何限制程序的执行时间?

标签 python subprocess kill

我想使用子进程来运行一个程序,我需要限制执行时间。比如运行超过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/

相关文章:

linux - sudo 忽略从同一脚本发送的 SIGTERM

python - 尝试将 dict_values 转换为 ipdb 中的列表时出错

python - 有没有办法用 django-mailer 发送 html 电子邮件?

用于类实例变量的对象方法链接的 Python 方式

python - 让子进程保持事件状态并继续向其发出命令? Python

c - 最后一个 fork 的 child 不会死

python - 通过将列表或字符串的列与另一个列表匹配来进行分组并创建新的数据框

python - subprocess.communicate() 仅在从脚本运行时神秘地挂起

python 子进程 check_output 损坏输出

c++ - 在 C++ 中 fork 和 kill 导致 ubuntu 崩溃