On Tue, Nov 23, 2010 at 1:15 PM, Ian <ian.g.ke...@gmail.com> wrote: > On Nov 23, 1:59 pm, Burton Samograd <bur...@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 -- http://mail.python.org/mailman/listinfo/python-list