Asked By – Pushpak Dagade
I have a large project consisting of sufficiently large number of modules, each printing something to the standard output. Now as the project has grown in size, there are large no. of
So, I now want to decide at runtime whether or not to print anything to the stdout. I cannot make changes in the modules as there are plenty of them. (I know I can redirect the stdout to a file but even this is considerably slow.)
So my question is how do I redirect the stdout to nothing ie how do I make the
# I want to do something like this. sys.stdout = None # this obviously will give an error as Nonetype object does not have any write method.
Currently the only idea I have is to make a class which has a write method (which does nothing) and redirect the stdout to an instance of this class.
class DontPrint(object): def write(*args): pass dp = DontPrint() sys.stdout = dp
Is there an inbuilt mechanism in python for this? Or is there something better than this?
Now we will see solution for issue: Redirecting stdout to “nothing” in python
import os import sys f = open(os.devnull, 'w') sys.stdout = f
f = open('nul', 'w') sys.stdout = f
f = open('/dev/null', 'w') sys.stdout = f