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

问题描述 投票:10回答:3

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

process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read()   # hangs here

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

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

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

python subprocess stdout popen hang
3个回答
1
投票

你可能想使用.communicate()而不是.wait()加上.read()。请注意wait()文档页面上有关subprocess的警告:

警告当使用stdout=PIPE和/或stderr=PIPE时,这将导致死锁,并且子进程会为管道生成足够的输出,以阻止等待OS管道缓冲区接受更多数据。使用communicate()来避免这种情况。

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


0
投票

read()在返回之前等待EOF。

您可以:

  • 等待子进程死掉,然后read()将返回。
  • 如果您的输出被分成几行,则使用readline()(如果没有输出行,则仍然会挂起)。
  • 使用os.read(F,N)从F返回最多N个字节,但如果管道为空,仍将阻塞(除非在fd上设置了O_NONBLOCK)。

0
投票

您可以在下一个源中看到如何处理stdout / stderr的挂起读取:

readingproc

© www.soinside.com 2019 - 2024. All rights reserved.