@contextlib.contextmanager<EOL>def captured_output(stream_name):
import io<EOL>orig_stdout = getattr(sys, stream_name)<EOL>setattr(sys, stream_name, io.StringIO())<EOL>try:<EOL><INDENT>yield getattr(sys, stream_name)<EOL><DEDENT>finally:<EOL><INDENT>setattr(sys, stream_name, orig_stdout)<EOL><DEDENT>
Run the 'with' statement body using a StringIO object in place of a
    specific attribute on the sys module.
    Example use (with 'stream_name=stdout')::

       with captured_stdout() as s:
           print "hello"
       assert s.getvalue() == "hello"