3

In Java, I can read the stdout as a string using

ByteArrayOutputStream stdout = new ByteArrayOutputStream();
System.setOut(new PrintStream(stdout));
String toUse = stdout.toString();

/**
 * do all my fancy stuff with string `toUse` here
 */

//Now that I am done, set it back to the console
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

Can someone please show me an equivalent way of doing this in python? I know different flavors of this question has been asked a number of times, such as Python: Closing a for loop by reading stdout and How to get stdout into a string (Python). But I have a feeling that I don't need to import subprocess to get what I need, as what I need is simpler than that. I am using pydev on eclipse, and I program is very simple.

I already tried

from sys import stdout

def findHello():
  print "hello world"
  myString = stdout

  y = 9 if "ell" in myString else 13

But that does not seem to be working. I get some compaints about opening file.

Community
  • 1
  • 1
learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

3

If I've understood what your trying to do properly, something like this will use a StringIO object to capture anything you write to stdout, which will allow you to get the value:

from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = stringio

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()

Of course, this suppresses the output actually going to the original stdout. If you want to print the output to the console, but still capture the value, you could use something like this:

class TeeOut(object):
    def __init__(self, *writers):
        self.writers = writers

    def write(self, s):
        for writer in self.writers:
            writer.write(s)

And use it like this:

from StringIO import StringIO
import sys

stringio = StringIO()
previous_stdout = sys.stdout
sys.stdout = TeeOut(stringio, previous_stdout)

# do stuff

sys.stdout = previous_stdout

myString = stringio.getvalue()
ig0774
  • 39,669
  • 3
  • 55
  • 57