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
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.
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.
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.
StdOut flushes standard output after each call to print() so that text will appear immediately in the terminal.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With