How to Suppress Standard Output (stdout) in Python
There are times when you want to prevent a Python script or a section of code from printing to the console (standard output, or stdout).
This guide explains how to effectively suppress stdout in Python, using the recommended contextlib.redirect_stdout context manager and, for completeness, discusses alternative (but less preferred) approaches.
Suppressing Output with contextlib.redirect_stdout (Recommended)
The contextlib.redirect_stdout context manager provides the safest and most Pythonic way to temporarily redirect stdout. To completely suppress output, redirect it to None:
import contextlib
with contextlib.redirect_stdout(None):
print('This gets redirected to nothing') # No output
print('This message is shown') # Output: This message is shown
with contextlib.redirect_stdout(None):: This creates a context. Inside thiswithblock, anything that would normally be printed tostdoutis suppressed.- Once the
withblock exits,stdoutis automatically restored to its original state. This is crucially important for preventing unintended side effects. You don't need to manually restorestdout.
Redirecting stdout to os.devnull (Less Recommended)
You can manually redirect stdout to os.devnull, which is a special file that discards all data written to it. However, this is generally not recommended because it's more error-prone and less readable than using contextlib.redirect_stdout. It's included here for completeness and to illustrate the correct way to do it if you must.
import sys
import os
try:
original_stdout = sys.stdout # Save the original stdout
with open(os.devnull, "w", encoding='utf-8') as target:
sys.stdout = target # Redirect stdout to os.devnull
print('This gets redirected to nothing') # No Output
finally:
sys.stdout = original_stdout # Restore stdout, ALWAYS!
print('This message is shown') # Output: This message is shown
original_stdout = sys.stdout: This line is absolutely essential. You must save the originalstdoutbefore changing it.with open(os.devnull, "w", encoding='utf-8') as target:: Opens the null device (/dev/nullon Unix-like systems,nulon Windows) in write mode.os.devnullhandles this cross-platform difference.sys.stdout = target: This redirectsstdoutto the opened null device. Allprintstatements and other output tostdoutwill now go to this "black hole."finally: sys.stdout = original_stdout: This is crucially important. Thefinallyblock ensures thatstdoutis always restored to its original value, even if an exception occurs within thetryblock. Failure to restorestdoutwill make it impossible to print anything to the console for the rest of the program's execution!sys.__stdout__can also be used instead of storing thestdoutto a variable.
Directly manipulating sys.stdout is risky.
If you forget to restore it, or if an exception occurs before restoration, your program will be unable to print anything to the console, making debugging extremely difficult. Always prefer contextlib.redirect_stdout(None).