How to suppress console output in Python?

Just for completeness, here’s a nice solution from Dave Smith’s blog:

from contextlib import contextmanager
import sys, os

@contextmanager
def suppress_stdout():
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:  
            yield
        finally:
            sys.stdout = old_stdout

With this, you can use context management wherever you want to suppress output:

print("Now you see it")
with suppress_stdout():
    print("Now you don't")

Leave a Comment