11
votes

Ok.. So probably an example is a good way to explain this problem

So I have something like this:

if __name__=="__main__"
    result = foobar()
    sys.stdout.write(str(result))
    sys.stdout.flush()
    sys.exit(0)

Now this script is being called from a ruby script.. and basically it parses the result there. But foobar() has a lot of print statments.. and stdout flushes all those prints as well. Is there a way (besides logging mathods) I can modify something over here which automatically suppresses those prints and just flushes this result?? Thanks

4

4 Answers

18
votes

You want to shadow (or otherwise hide) the stdout temporarily. Something like this:

actualstdout = sys.stdout
sys.stdout = StringIO()
result = foobar()
sys.stdout = actualstdout
sys.stdout.write(str(result))
sys.stdout.flush()
sys.exit(0)

You need to assign something that is file-like to sys.stdout so that other methods can use it effectively. StringIO is a good candidate because it doesn't require disk access (it'll just collect in memory) and then is discarded.

8
votes

With Python 3.4 and up you can use the redirect_stdout contextmanager like this:

with redirect_stdout(open(os.devnull, "w")):
    print("This text goes nowhere")
print("This text gets printed normally")
3
votes
import sys

class output:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)


if __name__=="__main__":

    out = output()                   
    sys.stdout = out                   #redirecting the output to a variable content

    result = foobar()
    sys.stdout.write(str(result))
    sys.stdout.flush() 

    sys.stdout = sys.__stdout__        #redirecting the output back to std output   
    print "o/p of foo :",out.content

    sys.exit(0)
1
votes

This link shows how to redirect stdout in python. Redirect it to an internal pipe, then read your pipe and filter out the unwanted lines. That will let you keep only the lines you are interested in.