Skip to content

Instantly share code, notes, and snippets.

@hvelarde
Created July 5, 2017 12:31
Show Gist options
  • Save hvelarde/d34566b8a49199b41703907959eb8ad9 to your computer and use it in GitHub Desktop.
Save hvelarde/d34566b8a49199b41703907959eb8ad9 to your computer and use it in GitHub Desktop.
A context manager to capture stdout and stderr
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