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.
Unless
stdout=PIPE
;p[0]
will always beNone
in your code.To get output of a command as a string, you could use
check_output()
:check_output()
usesstdout=PIPE
and.communicate()
internally.To read output from a file, you should call
.read()
on the file object: