# Write a context manager which temporarily replaces # sys.stdout with a io.StringIO() object and thus # captures the output of print(). import contextlib import sys import io @contextlib.contextmanager def capture_stdout(): r"""Replace sys.stdout with String() for the block. >>> with capture_stdout() as out: ... print('goo') >>> out.getvalue() 'goo\n' """ out = io.StringIO() old, sys.stdout = sys.stdout, out try: yield out finally: sys.stdout = old # To test this file, use: # py.test-3.4 --doctest-modules capture_stdout.py # or # python3 -m doctest capture_stdout.py