I found this block of code elsewhere on stackoverflow. I've been using it quite a bit, but now I can't seem to get any print function to work, no matter how many times I execute enablePrint()... any ideas?
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
and Print('test') results in no output. I'm doing this all in Juptyer.
In python 3 in order to work with WITH statement (context manager) you have to implement just two methods:
import os, sys
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._original_stdout
Then you can use it like this:
with HiddenPrints():
print("This will not be printed")
print("This will be printed as before")
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