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

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
2 min

banner

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

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.

main.py
import contextlib with contextlib.redirect_stdout(None): print('This gets redirected to nothing') print('This message is shown')

redirect stdout to nothing

The code for this article is available on GitHub

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.

You can also set the target to os.devnull which is the file path of the null device.

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

contextlib with os devnull

The code for this article is available on GitHub

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.

# Setting sys.stdout to os.devnull

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

try except os devnull

The code for this article is available on GitHub

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.