I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests.
How can I temporary redirect the stdout
in order to hide its output.
Limit to Python 2.5 syntax :)
Update, I forgot to mention that sys.stdout
and sys.__stderr__
methods do not work in this case. As far as I know this faulty module is using native code.
In Python, whenever we use print() the text is written to Python's sys. stdout, whenever input() is used, it comes from sys. stdin, and whenever exceptions occur it is written to sys. stderr.
To capture stdout output from a Python function call, we can use the redirect_stdout function. to call redirect_stdout with the f StringIO object. Then we call do_something which prints stuff to stdout. And then we get the value printed to stdout with f.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With