Python 子进程读取 stdout/stderr 如果程序在 < 10 秒内崩溃

Python subprocess reading stdout/stderr if the program crashes in < 10 seconds

我有一个脚本,它安排了另一个程序的长 运行s,有时可以 运行 并行(即我可以多次调用下面的函数)。我想解雇并忘记这些 children 所以我目前有:

p = subprocess.Popen(cmd, shell=False)
time.sleep(20)
result = p.poll()
if result is not None and result != 0:
    print("Child failed to start with exit code: {}".format(result))
    return False
return True

这在大多数情况下效果很好,但我想为 child 获取 stdout/stderr,但仅在 运行 失败超过 10 秒的情况下.

根据我的理解,使用 Popen(..., stdout=PIPE) 意味着如果我忽略子进程 object,那么缓冲区将填满并且 child 进程将挂起。

我怎样才能解决这个问题,使其不会挂起。是否有可能以某种方式将 PIPE 换成 None。

p = subprocess.Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE)
time.sleep(20)
result = p.poll()
if result is not None and result != 0:
    print("Child failed to start with exit code: {}".format(result))
    stdout, stderr = p.communicate()
    print("STDOUT:", stdout)
    print("STDERR:", stderr)
    return False
return True

同样可以安全地假设我可以轻松地将在前 10 秒内生成的输出保存在缓冲区中。

一个简单的方法是将所有 children 写入临时文件 (https://docs.python.org/2/library/tempfile.html)。只写在那里而不是管道,只在需要时读取文件(如果发生崩溃)。