Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

suppressing print as stdout python

Tags:

python

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

like image 816
frazman Avatar asked Mar 30 '12 19:03

frazman


People also ask

How do you disable stdout in python?

suppress stdout and stderr with context managerUse suppress_stdout and suppress_stderr flags to indicate which stream to be suppressed. Save the state of the sys. stdout and sys. stderr in the __enter__ function, and redirect them to devnull based on the suppress_stdout and suppress_stderr flags.

How do you suppress print function in Python?

If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.

Does print in Python go to stdout?

print() and Standard Out. Every running program has a text output area called "standard out", or sometimes just "stdout". The Python print() function takes in python data such as ints and strings, and prints those values to standard out.

Does print go to stdout?

StdOut flushes standard output after each call to print() so that text will appear immediately in the terminal.


2 Answers

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.

like image 106
g.d.d.c Avatar answered Sep 18 '22 15:09

g.d.d.c


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")
like image 40
Felk Avatar answered Sep 22 '22 15:09

Felk