Capture stdout from a script? Capture stdout from a script? python python

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()


Setting stdout is a reasonable way to do it. Another is to run it as another process:

import subprocessproc = subprocess.Popen(["python", "-c", "import writer; writer.write()"], stdout=subprocess.PIPE)out = proc.communicate()[0]print out.upper()


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'