Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read python stdout as string

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.

like image 939
learner Avatar asked Nov 15 '25 00:11

learner


1 Answers

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()
like image 108
ig0774 Avatar answered Nov 17 '25 21:11

ig0774



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!