使用 NamedTemporaryFile 通过 Linux 上的子进程从 stdout 读取

Use NamedTemporaryFile to read from stdout via subprocess on Linux

import subprocess
import tempfile

fd = tempfile.NamedTemporaryFile()
print(fd)
print(fd.name)
p = subprocess.Popen("date", stdout=fd).communicate()
print(p[0])
fd.close()

这个returns:

<open file '<fdopen>', mode 'w' at 0x7fc27eb1e810>
/tmp/tmp8kX9C1
None

相反,我希望它 return 类似于:

Tue Jun 23 10:23:15 CEST 2015

我尝试添加 mode="w" 以及 delete=False,但无法成功。

除非stdout=PIPEp[0] 在您的代码中将永远是 None

要将命令输出作为字符串,您可以使用 check_output():

#!/usr/bin/env python
from subprocess import check_output

result = check_output("date")

check_output() uses stdout=PIPE and .communicate() internally.

要从文件中读取输出,您应该对文件对象调用 .read()

#!/usr/bin/env python
import subprocess
import tempfile

with tempfile.TemporaryFile() as file:
    subprocess.check_call("date", stdout=file)
    file.seek(0) # sync. with disk
    result = file.read()