Collect output to string

Ian ian.g.kelly at
Tue Nov 23 22:15:46 CET 2010

On Nov 23, 1:59 pm, Burton Samograd <bur... at> 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

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.


More information about the Python-list mailing list