Reputation: 6302
I am trying to run an external program (in this case just python -V) and capture the standard error in the memory.
It works if I redirect to disk:
import sys, os
import subprocess
import tempfile
err = tempfile.mkstemp()
print err[1]
p = subprocess.call([sys.executable, '-V'], stderr=err[0] )
but that's not fun. Then I'd need to read that file into memory.
I thought I can create something in-memory that would act like a file using StringIO but this attempt failed:
import sys, os
import subprocess
import tempfile
import StringIO
err = StringIO.StringIO()
p = subprocess.call([sys.executable, '-V'], stderr=err )
I got:
AttributeError: StringIO instance has no attribute 'fileno'
ps. Once this works I'll want to capture stdout as well, but I guess that's the same. ps2. I tried the above on Windows and Python 2.7.3
Upvotes: 0
Views: 2100
Reputation: 4504
Use subprocess.check_output. From the docs
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Run command with arguments and return its output as a byte string.
Upvotes: 0
Reputation: 309889
You need to set stderr = subprocess.PIPE
e.g.:
p = subprocess.Popen(...,stderr = subprocess.PIPE)
stdout,stderr = p.communicate()
#p.stderr.read() could work too.
note, for this to work, you need access to the Popen
object, so you can't really use subprocess.call
here (you really need subprocess.Popen
).
Upvotes: 2