【问题标题】:subprocess fail to kill make command子进程无法杀死 make 命令
【发布时间】:2021-08-02 20:26:17
【问题描述】:

如果我在subprocess.Popen 中运行'make' 命令,它不会在超时后终止

    with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
    try:
        stdout, stderr = process.communicate(input, timeout=timeout)
    except subprocess.TimeoutExpired:
        process.kill()
        stdout, stderr = process.communicate()

我试过了

subprocess.check_output and subprocess.run

它们也不起作用。

如果使用上述方法独立运行 Makefile 中的每个命令,则可以正常工作。

【问题讨论】:

  • 如果不重定向输入,为什么还要传递一些输入?
  • @Jean-FrançoisFabre 在我的情况下输入无关紧要。是的,它可以被删除。问题是“make”命令不会终止。在 Makefile 中有一个带有无限循环的程序启动,如果我以这种方式运行它而不是“make”,它就会被成功杀死

标签: python makefile subprocess


【解决方案1】:

在使用subprocess 时,我经常尝试追求最简单的路径来获得所需的结果。话虽如此,我还是建议您在被调用的脚本中添加一个超时时间,而无需尝试杀死它。

例如:

timeout_length = 30 # seconds
command = "make"
subprocess.Popen(['timeout', timeout_length, command], 
                 stdout=subprocess.PIPE, 
                 stderr=subprocess.PIPE)

【讨论】:

  • 谢谢,它在 Linux 上运行良好,但在 MacOS 上没有超时。有一个替代方案,但它使程序平台依赖和/或需要额外的工具来安装
  • subprocess.run 和朋友们有一个 timeout 关键字参数;也许使用裸露的PopenPopen 文档特别建议您应该避免使用它,并尽可能使用更高级别的 subprocess 函数。
【解决方案2】:

一个经典的问题是

process.kill()

不会杀死子进程。也许在你的情况下,一个子进程正在运行并且没有停止,特别是如果主makefile调用其他makefile。

在这种情况下,将answer 中的配方应用到how to kill process and child processes from python?

import psutil

with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
try:
    stdout, stderr = process.communicate(input, timeout=timeout)
except subprocess.TimeoutExpired:
    # create a parent psutil process object
    parent = psutil.Process(process.pid)
    # list all child processes and kill them
    for child in parent.children(recursive=True):  # or parent.children() for recursive=False
       child.kill()
    # kill parent process as done earlier
    process.kill()
    stdout, stderr = process.communicate()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    相关资源
    最近更新 更多