Python Popen().stdout.read()挂起 [英] Python Popen().stdout.read() hang

查看:566
本文介绍了Python Popen().stdout.read()挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用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/or stderr=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. Use communicate() to avoid that.

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

这篇关于Python Popen().stdout.read()挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆