Collect output to string

Hrvoje Niksic hniksic at xemacs.org
Wed Nov 24 17:09:25 EST 2010


Burton Samograd <burton at userful.com> writes:

> Terry Reedy <tjreedy at udel.edu> 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

@contextlib.contextmanager
def output_to_string():
    oldout = sys.stdout
    sys.stdout = cStringIO.StringIO()
    try:
        yield sys.stdout
    finally:
        sys.stdout = oldout

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



More information about the Python-list mailing list