Last updated: Apr 9, 2024
Reading time·2 min

Use the redirect_stdout method from the contextlib module to redirect
stdout to nothing.
The redirect_stdout() method can be passed a None value to ignore the
output of stdout.
import contextlib with contextlib.redirect_stdout(None): print('This gets redirected to nothing') print('This message is shown')

The
contextlib.redirect_stdout()
method takes a target and temporarily redirects sys.stdout to the specified
target.
We used a None object as the target to redirect the output of sys.stdout to
nothing.
print() and help() functions is set to sys.stdout by default so printing any messages in the with block has no effect.You can also set the target to
os.devnull which is the
file path of the null device.
import sys import os import contextlib with contextlib.redirect_stdout(open(os.devnull, 'w', encoding='utf-8')): sys.stdout.write('This gets redirected to nothing') sys.stdout.write('This message is shown')

The os.devnull property is set to /dev/null for POSIX and nul for Windows.
Once you exit the with block,
the value of sys.stdout gets set to the default.
sys.stdout to os.devnullAlternatively, you can use set sys.stdout to
os.devnull, which is the
file path of the null device.
The file path of the null device is /dev/null on Unix and nul on Windows.
import sys import os try: with open(os.devnull, "w", encoding='utf-8') as target: sys.stdout = target print('This gets redirected to nothing') finally: sys.stdout = sys.__stdout__ print('This message is shown')

We redirected sys.stdout to /dev/null in the try block and restored it to
the default in the finally block.
The
sys.__stdout__
object contains the original value of sys.stdout.
You can use the object to restore sys.stdout to its original value.