Collect output to string

Hrvoje Niksic hniksic at
Wed Nov 24 23:09:25 CET 2010

Burton Samograd <burton at> writes:

> Terry Reedy <tjreedy at> writes:
>> On 11/23/2010 3:02 PM, Chris Rebert wrote:
>> If you are using print or print(), you can redirect output to the
>> StringIO object with >>sfile or file=sfile. I use the latter in a
>> custom test function where I normally want output to the screen but
>> occasionally want to capture test reports.
> Thanks for the info, but I was looking for a way to collect output
> without modifying the original function, similar to
> with-output-to-string in some schemes.

Redirecting output like with-output-to-string does is achieved by
assigning to sys.stdout.  Using contextlib you can make it even closer
to with-output-to-string by deploying the actual with statement.
Unfortunately python's with cannot return a value, so you must expose
the StringIO to the caller.  The result is still quite nice:

import sys, contextlib, cStringIO

def output_to_string():
    oldout = sys.stdout
    sys.stdout = cStringIO.StringIO()
        yield sys.stdout
        sys.stdout = oldout

>>> with output_to_string() as out:
...   print 'foo'
...   print 'bar'
>>> out.getvalue()

More information about the Python-list mailing list