【问题标题】:Use NamedTemporaryFile to read from stdout via subprocess on Linux在 Linux 上使用 NamedTemporaryFile 通过子进程从标准输出读取
【发布时间】:2015-06-23 08:37:20
【问题描述】:
import subprocess
import tempfile

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

这会返回:

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

相反,我希望它返回如下内容:

Tue Jun 23 10:23:15 CEST 2015

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

【问题讨论】:

  • 你知道subprocess.check_output()吗?
  • @J.F.Sebastian 是的。事实上,我希望传递给系统的命令是qstat -xml -r*.com/a/26104540/597069)。不幸的是,它的行为似乎与 date 不同。
  • 如果需要qstat的输出;你应该询问qstat。好像是XY problem。为什么这里需要NamedTemporaryFile

标签: python-2.7 subprocess temporary-files


【解决方案1】:

除非stdout=PIPE; p[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()

【讨论】: