Collect output to string
MRAB
python at mrabarnett.plus.com
Tue Nov 23 16:17:53 EST 2010
On 23/11/2010 20:59, Burton Samograd wrote:
> Chris Rebert<clp2 at rebertia.com> writes:
>
>> On Tue, Nov 23, 2010 at 11:53 AM, Burton Samograd<burton at userful.com> 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?
>
Use a try...finally block in an exception occurs:
try:
apply(f, args)
finally:
sys.stdout = oldstdout
and possibly also replace the older:
apply(f, args)
with the newer:
f(*args)
You might also want to handle keyword arguments.
More information about the Python-list
mailing list