Created
July 5, 2017 12:31
-
-
Save hvelarde/d34566b8a49199b41703907959eb8ad9 to your computer and use it in GitHub Desktop.
A context manager to capture stdout and stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextlib | |
@contextlib.contextmanager | |
def capture(): | |
"""A context manager to capture stdout and stderr. | |
http://stackoverflow.com/a/10743550/644075 | |
""" | |
import sys | |
from cStringIO import StringIO | |
oldout, olderr = sys.stdout, sys.stderr | |
try: | |
out = [StringIO(), StringIO()] | |
sys.stdout, sys.stderr = out | |
yield out | |
finally: | |
sys.stdout, sys.stderr = oldout, olderr | |
out[0], out[1] = out[0].getvalue(), out[1].getvalue() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment