Redirect stdout to nothing (/dev/null) in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

Redirect stdout to nothing (/dev/null) in Python #

Use the contextlib module to redirect stdout to nothing, e.g. with contextlib.redirect_stdout(None):. The redirect_stdout() method can be passed a None value to ignore the output of stdout.

main.py
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.

The output of the print() and help() functions is set to sys.stdout by default so printing any messages in the with block has no effect.

Once you exit the with block, the value of sys.stdout gets set to the default.

Alternatively, 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.

main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.