Use NamedTemporaryFile to read from stdout via subprocess on Linux

398 views Asked by At
import subprocess
import tempfile

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

This returns:

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

Instead, I would like it to return something like:

Tue Jun 23 10:23:15 CEST 2015

I tried adding mode="w", as well as delete=False, but can't succeed to make it work.

1

There are 1 answers

0
jfs On BEST ANSWER

Unless stdout=PIPE; p[0] will always be None in your code.

To get output of a command as a string, you could use check_output():

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

result = check_output("date")

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

To read output from a file, you should call .read() on the file object:

#!/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()