Python Popen().stdout.read()挂起 [英] Python Popen().stdout.read() hang
问题描述
我正尝试使用Python的subprocess.Popen
来获取另一个脚本的输出,如下所示
I'm trying to get output of another script, using Python's subprocess.Popen
like follows
process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read() # hangs here
仅当我将其作为python脚本运行并且无法在python shell中重现时,它才挂在第三行.
It hangs at the third line, only when I run it as a python script and I cannot reproduce this in the python shell.
另一个脚本仅输出几个单词,我认为这不是缓冲区问题.
The other script prints just a few words and I am assuming that it's not a buffer issue.
有人知道我在做什么错吗?
Does anyone has idea about what I am doing wrong here?
推荐答案
You probably want to use .communicate()
rather than .wait()
plus .read()
. Note the warning about wait()
on the subprocess
documentation page:
警告当使用
stdout=PIPE
和/或stderr=PIPE
时,这将导致死锁,并且子进程会向管道生成足够的输出,从而阻塞等待OS管道缓冲区接受更多数据的等待.使用communicate()
可以避免这种情况.
Warning This will deadlock when using
stdout=PIPE
and/orstderr=PIPE
and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Usecommunicate()
to avoid that.
http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
这篇关于Python Popen().stdout.read()挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!