11

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 Answers 4

18

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.

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

7 Comments

awesome.. just what i needed :)
What about using sys.stdout = open(os.devnull,'w') instead of StringIO()?
@ovgolovin - definitely reasonable as well if there's no expectation you might ever need the output. With StringIO you could retrieve it if needed before you reset the original value of stdout.
for anyone coming along like I did... don't try this inside an ipython console :)
|
9

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

Comments

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.