Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python + Disabled print output, and can't get it back

Tags:

python

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.

like image 592
keynesiancross Avatar asked Jul 10 '26 04:07

keynesiancross


1 Answers

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")
like image 52
Alexander C Avatar answered Jul 13 '26 16:07

Alexander C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!