0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

The documentation recommends against that: "Do not use stdout=PIPE or stderr=PIPE with this function. " or is that different than subprocess.PIPE that you suggest ?
@szabgab -- Sorry, I must have been editing while you were commenting. You can't use PIPE with subprocess.call (or at least you shouldn't). You can use it with subprocess.Popen as I have demonstrated in my answer.
Indeed, my previous comment was made when only the first line of the answer was seen. subprocess.Popen worked nicely. Thanks
@szabgab -- Sorry. I suppose I should have taken my time a little more to write a bit more to the answer before hitting the original submit :)
@mgilson no problem, I just wanted to clarify my comment in a comment in a comment ... :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.