Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)
Simo Melenius
firstname.lastname at iki.fi-spam
Mon Jan 3 04:34:06 EST 2005
Ron Garret <rNOSPAMon at flownet.com> writes:
> (with-output-to-string (s)
> (let ( (*standard-output* s) )
> (call-html-generating-code)
> s))
>
> Is there an equivalent Python trick to capture a function call's output
> as a string?
I've sometimes replaced sys.stdout (and/or sys.stderr) to
capture/redirect debugging information in existing code that has
unwisely just "print"ed error and warning messages, instead of using
sys.stderr or error logging modules.
py> def with_output_to_string (func):
... try:
... sys.stdout = StringIO.StringIO ()
... func ()
... return sys.stdout.getvalue ()
... finally:
... sys.stdout = sys.__stdout__
...
py> def printing_code ():
... print "Foobar"
...
py> with_output_to_string (printing_code)
'Foobar\n'
py>
br,
S
More information about the Python-list
mailing list