Capture stdout from a script?
For future visitors: Python 3.4 contextlib provides for this directly (see Python contextlib help) via the redirect_stdout
context manager:
from contextlib import redirect_stdoutimport iof = io.StringIO()with redirect_stdout(f): help(pow)s = f.getvalue()
Here is a context manager version of your code. It yields a list of two values; the first is stdout, the second is stderr.
import contextlib@contextlib.contextmanagerdef capture(): import sys from cStringIO import StringIO oldout,olderr = sys.stdout, sys.stderr try: out=[StringIO(), StringIO()] sys.stdout,sys.stderr = out yield out finally: sys.stdout,sys.stderr = oldout, olderr out[0] = out[0].getvalue() out[1] = out[1].getvalue()with capture() as out: print 'hi'