Skip to content

Instantly share code, notes, and snippets.

@ionelmc
Created June 23, 2014 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ionelmc/7455fb088768d40326b1 to your computer and use it in GitHub Desktop.
Save ionelmc/7455fb088768d40326b1 to your computer and use it in GitHub Desktop.
class CaptureOutput(object):
def __init__(self, *what):
self.__names = set(what)
self.__objects = {}
for name in self.__names:
assert isinstance(name, str)
assert name in ('stderr', 'stdout', '__stderr__', '__stdout__')
def __enter__(self):
for name in self.__names:
self.__objects[name] = getattr(sys, name)
buff = StringIO()
setattr(sys, name, buff)
setattr(self, name, buff)
return self
def __exit__(self, evalue=None, etype=None, tb=None):
for name, original in self.__objects.items():
setattr(sys, name, original)
setattr(self, name, getattr(self, name).getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment