Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)

JanC usenet_spam at janc.invalid
Mon Jan 3 04:01:07 EST 2005

Ron Garret schreef:

> But this topic does bring up a legitimate question: I have a bunch of 
> code that generates HTML using PRINT statements.  I need to convert all 
> this code to return strings rather than actually printing them (so I can 
> use the results to populate templates).  In Lisp I could do this:
> (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?

Something like this:

py> import cStringIO
py> import sys
py> def foo():
...     print "test"
py> f = cStringIO.StringIO()
py> sys.stdout = f
py> foo()
py> s = f.getvalue()
py> sys.stdout = sys.__stdout__
py> f.close()
py> print s.capitalize()


"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9

More information about the Python-list mailing list