Collect output to string

Ian ian.g.kelly at gmail.com
Tue Nov 23 16:15:46 EST 2010


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.

Cheers,
Ian



More information about the Python-list mailing list