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")

You can get around this by assigning the standard out/error (I don't know which one it's going to) to the null device. In Python, the standard out/error files are sys.stdout/sys.stderr, and the null device is os.devnull, so you do

sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")

This should disable these error messages completely. Unfortunately, this will also disable all console output. To get around this, disable output right before calling the get_hat() the method, and then restore it by doing

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

which restores standard out and error to their original value.


To complete charles's answer, there are two context managers built in to python, redirect_stdout and redirect_stderr which you can use to redirect and or suppress a commands output to a file or StringIO variable.

import contextlib

with contextlib.redirect_stdout(None):
    do_thing()

For a more complete explanation read the docs

A quick update: In some cases passing None might raise some reference errors (e.g. keras.models.Model.fit calls sys.stdout.write which will be problematic), in that case pass an io.StringIO() or os.devnull.

Tags:

Python

Pygame

Sdl