class CaptureOutput(object): """Context manager that captures what's written to :py:data:`sys.stdout`.""" def __init__(self): """Initialize a string IO object to be used as :py:data:`sys.stdout`.""" self.stream = StringIO() def __enter__(self): """Start capturing what's written to :py:data:`sys.stdout`.""" self.original_stdout = sys.stdout sys.stdout = self.stream return self def __exit__(self, exc_type=None, exc_value=None, traceback=None): """Stop capturing what's written to :py:data:`sys.stdout`.""" sys.stdout = self.original_stdout def __str__(self): """Get the text written to :py:data:`sys.stdout`.""" return self.stream.getvalue()
def __init__(self): """Initialize a string IO object to be used as :py:data:`sys.stdout`.""" self.stream = StringIO()