0

Similar to this post, I used the code from the highest voted answer on this post

import sys, os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

blockPrint()
print("This won't")

and now I cannot restore calls to print. Unfortunately, none of the suggested approaches from the first mentioned stackoverflow question have worked for me.

Here are the following approaches I have tried, as suggested from the aforementioned posts:

import sys, os

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__

enablePrint()
print("test")
from contextlib import contextmanager

@contextmanager
def blockPrint():
    import sys
    old_stdout = sys.stdout
    sys.stdout = None
    try:
        yield
    finally:
        sys.stdout = old_stdout

with blockPrint():
    print("test")

print("test")
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
with HiddenPrints():
    print("This will not be printed")

print("This will be printed as before")

Of course I would share the output, but there is none. I should note that I was only trying to block print calls from a specific function (basically, I wanted to have a "verbose" function parameter). I'm using JupyterLab running Python 3.

0 Answers0