Created
June 23, 2014 13:32
-
-
Save ionelmc/7455fb088768d40326b1 to your computer and use it in GitHub Desktop.
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
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