我正在尝试获取另一个脚本的输出,使用Python的subprocess.Popen
,如下所示
process = Popen(command, stdout=PIPE, shell=True)
exitcode = process.wait()
output = process.stdout.read() # hangs here
它挂在第三行,只有当我将它作为python脚本运行时,我无法在python shell中重现它。
另一个脚本只打印几个单词,我假设它不是缓冲区问题。
有谁知道我在做错了什么?
你可能想使用.communicate()
而不是.wait()
加上.read()
。请注意wait()
文档页面上有关subprocess
的警告:
警告当使用
stdout=PIPE
和/或stderr=PIPE
时,这将导致死锁,并且子进程会为管道生成足够的输出,以阻止等待OS管道缓冲区接受更多数据。使用communicate()
来避免这种情况。
http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
read()在返回之前等待EOF。
您可以:
您可以在下一个源中看到如何处理stdout / stderr的挂起读取: