# Write a context manager which temporarily replaces # sys.stdout with a io.StringIO() object and thus # captures the output of print(). import contextlib @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' """ try: yield ... finally: pass # To test this file, use: # py.test-3.4 --doctest-modules capture_stdout.py # or # python3 -m doctest capture_stdout.py