Collect output to string

Chris Rebert clp2 at rebertia.com
Tue Nov 23 22:42:10 CET 2010


On Tue, Nov 23, 2010 at 1:15 PM, Ian <ian.g.kelly at gmail.com> wrote:
> On Nov 23, 1:59 pm, Burton Samograd <bur... at userful.com> wrote:
>> Thanks for the tip.  Here's my function:
>>
>> def with_output_to_string(f, args):
>>      oldstdout = sys.stdout
>>      buffer = StringIO.StringIO()
>>      sys.stdout = buffer
>>      apply(f, args)
>>      sys.stdout = oldstdout
>>      return buffer.getvalue()
>>
>> Any way I could improve it?
>
> You should wrap the inner function call in a try-finally call to
> ensure that the old stdout gets restored even if f raises an
> exception.
>
> Also, the `apply` function is deprecated.  Use `f(*args)` instead.
>
> The function as a whole would be a bit more Pythonic if written as a
> decorator IMO, but that's your call.

A context manager could also be worth considering.
http://docs.python.org/library/stdtypes.html#context-manager-types

Cheers,
Chris



More information about the Python-list mailing list