无法成功将标准输出从 Popen 重定向到临时文件

Cannot successfully redirect stdout from Popen to temp file

标题说明了一切,真的。当前 运行 Python 2.7.8,使用 subprocess32。最小复制片段,直接从 REPL 复制:

Python 2.7.8 (default, Aug 14 2014, 13:26:38)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> import subprocess32 as subp
>>> tfil = tempfile.TemporaryFile()
>>> tfil
<open file '<fdopen>', mode 'w+b' at 0x7f79dcf158a0>
>>> proc = subp.Popen(['ls', '-al'], stdout=tfil, stderr=subp.STDOUT)
>>> proc
<subprocess32.Popen object at 0x7f79dcf04a50>
>>> proc.wait()
0
>>> tfil.read()
''
>>>

对结果没有影响的代码更改,任意组合:

我需要这样做,因为我想在实际 non-minimal-example 程序 (qacct -j) 中使用的命令的输出对于 subprocess.PIPE 来说太大了,引发 MemoryError(没有进一步的细节)。

我发现的最相关的现有问题是 this,但实际上并没有帮助。

文件已正确写入,但您的 tfil.read() 命令将从上次写入发生的位置开始读取,因此它 return 什么也不会。您需要先致电tfil.seek(0)