Rebinding stdout

Mark McEahern marklists at
Sun Jan 2 15:43:34 EST 2005

Ron Garret wrote:

> 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?
Just to make sure I understand, I'm going to restate your question:

Is there a way to capture stdout?

The answer:  Sure, replace it with something file-like:

 >>> import sys, StringIO
 >>> default = sys.stdout
 >>> writer = StringIO.StringIO()
 >>> sys.stdout = writer
 >>> print 'Whatever'
 >>> sys.stdout = default
 >>> print writer.getvalue()


// m

More information about the Python-list mailing list