How to temporary hide stdout or stderr while running a unittest in Python

You can do it something like this:

>>> import sys, os
>>> _stderr = sys.stderr
>>> _stdout = sys.stdout
>>> null = open(os.devnull,'wb')
>>> sys.stdout = sys.stderr = null
>>> print("Bleh")
>>> sys.stderr = _stderr
>>> sys.stdout = _stdout
>>> print("Bleh")
Bleh

You can also use mock to let you patch sys.stdout and sys.stderr for you when the module is imported. An example of a testing module that using this strategy would be:

import os
devnull = open(os.devnull, 'w')

from mock import patch
with patch('sys.stdout', devnull):
    with patch('sys.stderr', devnull):
        import bad_module

# Test cases writen here

where bad_module is the third party module that is printing to sys.stdout and sys.stderr when is being imported.

Tags:

Python