@contextmanager
def captured(disallow_stderr=True):
 import sys
 stdout = sys.stdout
 stderr = sys.stderr
 sys.stdout = outfile = StringIO()
 sys.stderr = errfile = StringIO()
 c = CapturedText()
 try:
  (yield c)
 finally:
  c.stdout = outfile.getvalue()
  c.stderr = strip_expected(errfile.getvalue())
  sys.stdout = stdout
  sys.stderr = stderr
  if (disallow_stderr and c.stderr):
   raise Exception(('Got stderr output: %s' % c.stderr))

@ contextmanager def captured ( disallow_stderr = True ) : import sys stdout = sys . stdout stderr = sys . stderr sys . stdout = outfile = StringIO ( ) sys . stderr = errfile = StringIO ( ) c = CapturedText ( ) try : ( yield c ) finally : c . stdout = outfile . getvalue ( ) c . stderr = strip_expected ( errfile . getvalue ( ) ) sys . stdout = stdout sys . stderr = stderr if ( disallow_stderr and c . stderr ) : raise Exception ( ( 'Got stderr output: %s' % c . stderr ) )
context manager to capture the printed output of the code in the with block bind the context manager to a variable using as and the result will be in the stdout property .