Skip to content

How to Suppress Standard Output (stdout) in Python

Learn how to temporarily suppress console output in Python using contextlib.redirect_stdout and alternative methods like os.devnull for debugging or silent execution.

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.

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 this with block, anything that would normally be printed to stdout is suppressed.
  • Once the with block exits, stdout is automatically restored to its original state. This is crucially important for preventing unintended side effects. You don't need to manually restore stdout.

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 original stdout before changing it.
  • with open(os.devnull, "w", encoding='utf-8') as target:: Opens the null device (/dev/null on Unix-like systems, nul on Windows) in write mode. os.devnull handles this cross-platform difference.
  • sys.stdout = target: This redirects stdout to the opened null device. All print statements and other output to stdout will now go to this "black hole."
  • finally: sys.stdout = original_stdout: This is crucially important. The finally block ensures that stdout is always restored to its original value, even if an exception occurs within the try block. Failure to restore stdout will 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 the stdout to a variable.
Navigation