How to block calls to print? How to block calls to print? python python

How to block calls to print?


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# Disabledef blockPrint():    sys.stdout = open(os.devnull, 'w')# Restoredef 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.


Use with

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

import os, sysclass 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 exceptionexcept 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 osimport contextlibwith open(os.devnull, "w") as f, contextlib.redirect_stdout(f):    print("This won't be printed.")