Chris Rebert <[email protected]> writes:
> On Tue, Nov 23, 2010 at 11:53 AM, Burton Samograd <[email protected]> wrote:
>> Hello,
>>
>> I was wondering if there is any way in python to 'collect output to
>> string' as in some lisps/schemes. Output being, printed output to the
>> console using print.
>
> Rebind sys.stdout to a StringIO object.
> http://docs.python.org/library/sys.html#sys.stdout
> http://docs.python.org/library/stringio.html
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?
--
Burton Samograd
--
http://mail.python.org/mailman/listinfo/python-list