How to block calls to print?

Use with

Based on @FakeRainBrigand solution I'm suggesting a safer solution:

import os, sys

class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout

Then you can use it like this:

with HiddenPrints():
    print("This will not be printed")

print("This will be printed as before")

This is much safer because you can not forget to re-enable stdout, which is especially critical when handling exceptions.

Without with — Bad practice

The following example uses enable/disable prints functions that were suggested in previous answer.

Imagine that there is a code that may raise an exception. We had to use finally statement in order to enable prints in any case.

try:
    disable_prints()
    something_throwing()
    enable_prints() # This will not help in case of exception
except ValueError as err:
    handle_error(err)
finally:
    enable_prints() # That's where it needs to go.

If you forgot the finally clause, none of your print calls would print anything anymore.

It is safer to use the with statement, which makes sure that prints will be reenabled.

Note: It is not safe to use sys.stdout = None, because someone could call methods like sys.stdout.write()


As @Alexander Chzhen suggested, using a context manager would be safer than calling a pair of state-changing functions.

However, you don't need to reimplement the context manager - it's already in the standard library. You can redirect stdout (the file object that print uses) with contextlib.redirect_stdout, and also stderr with contextlib.redirect_stderr.

import os
import contextlib

with open(os.devnull, "w") as f, contextlib.redirect_stdout(f):
    print("This won't be printed.")

Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.

import sys, os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__


print 'This will print'

blockPrint()
print "This won't"

enablePrint()
print "This will too"

If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.