@contextlib.contextmanager
def captured_output(stream_name):
 import StringIO
 orig_stdout = getattr(sys, stream_name)
 setattr(sys, stream_name, StringIO.StringIO())
 try:
  (yield getattr(sys, stream_name))
 finally:
  setattr(sys, stream_name, orig_stdout)

@ contextlib . contextmanager def captured_output ( stream_name ) : import StringIO orig_stdout = getattr ( sys , stream_name ) setattr ( sys , stream_name , StringIO . StringIO ( ) ) try : ( yield getattr ( sys , stream_name ) ) finally : setattr ( sys , stream_name , orig_stdout )
return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a stringio .