0
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.

tflutre
  • 3,354
  • 9
  • 39
  • 53
  • are you aware of `subprocess.check_output()`? – jfs Jun 23 '15 at 08:47
  • @J.F.Sebastian yes. In fact, the command I wish to pass to the system is `qstat -xml -r` (http://stackoverflow.com/a/26104540/597069). Unfortunately, it seems to behave differently than `date`. – tflutre Jun 23 '15 at 08:49
  • If you need output of `qstat`; you should ask about `qstat`. It seems like [XY problem](http://meta.stackexchange.com/a/66378/137096). Why do you need `NamedTemporaryFile` here? – jfs Jun 23 '15 at 08:51

1 Answers1

0

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()
jfs
  • 399,953
  • 195
  • 994
  • 1,670