python - 如果 stdout=PIPE,我如何找出 subprocess.Popen wait() 永远等待的原因?

标签 python subprocess

我有一个写入标准输出和可能的标准错误的程序。我想从 python 运行它,捕获标准输出和标准错误。我的代码如下所示:

from subprocess import *

p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE )
rtrncode = p.wait()

对于几个程序,这工作正常,但是当我添加一个新程序时,新程序永远挂起。如果我删除 stdout=PIPE,程序会将其输出写入控制台并完成,一切正常。如何确定导致挂起的原因?

在 Windows XP 上使用 python 2.5。该程序不从标准输入读取,也没有任何类型的用户输入(即“按一个键”)。

最佳答案

当管道缓冲区填满(通常为 4KB 左右)时,写入过程将停止,直到读取过程读取了一些有问题的数据;但是在这里,在子流程完成之前您什么都看不到,因此出现了死锁。 The docswait 上确实非常清楚:

Warning This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

如果由于某种原因你不能使用communicate,让子进程写入一个临时文件,然后你可以等待并在文件准备好时读取它 - - 写入文件而不是管道,不会有死锁的风险。

关于python - 如果 stdout=PIPE,我如何找出 subprocess.Popen wait() 永远等待的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54189344/

相关文章:

python - 子进程相对于 os.system 的优势

python - OpenERP 字段保存时间值,例如 `08:04`

python - 如何对齐 QGraphicsTextItem 的网格?

Python Pygame 不会退出

python - 如何在Python中按升序对前半部分进行升序对后半部分进行降序排序?

python - 难以捕获执行就地状态更新的子流程的输出

python - subprocess.check_call([PYTHON_PATH, try_str[i]]) 系统找不到指定文件

python - Popen 管道 2 cmd 挂起并且没有给出预期的结果

Java:通过进程控制浏览器

python - 在 exe 中使用从 DLL 导出的 Python 对象