Last Updated: February 25, 2016
·
185
· mattsirocki

Python Silencer (Context Manager)

For when you need to keep some code quiet.

class Silencer(object):
    """ Creates a silent context. All output to the given file-like
        objects is instead sent to /dev/null.
    """
    def __init__(self, *files):
        self._files = files

    def __enter__(self):
        self._dupes = {x.fileno(): os.dup(x.fileno()) for x in self._files}

        null = open(os.devnull, 'ab')
        for x in self._files:
            x.flush()
            os.dup2(null.fileno(), x.fileno())
        null.close()

    def __exit__(self, *args):
        for x in self._files:
            x.flush()
            os.dup2(self._dupes[x.fileno()], x.fileno())
            os.close(self._dupes[x.fileno()])

You can use it like this:

with Silencer(sys.stdout, sys.stderr):
    print 'I will not be seen.'
    sys.stdout.write('me neither')
    sys.stderr.write('me three')