Python Popen().stdout.read()挂起

lyo*_*omi 10 python subprocess stdout popen hang

我正在尝试获取另一个脚本的输出,使用Python subprocess.Popen如下

process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read()   # hangs here
Run Code Online (Sandbox Code Playgroud)

它挂在第三行,只有当我将它作为python脚本运行时,我无法在python shell中重现它.

另一个脚本只打印几个单词,我假设它不是缓冲区问题.

有谁知道我在做错了什么?

Amb*_*ber 5

您可能想要使用.communicate()而不是.wait()plus .read()。请注意文档页面wait()上的警告subprocess

警告这将在使用stdout=PIPE和/或时死锁,并且stderr=PIPE子进程向管道生成足够的输出,从而阻止等待操作系统管道缓冲区接受更多数据。使用communicate()以避免这种情况。

http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait