[Tutor] buffering print statement

Terry Carroll carroll at tjc.com
Thu Dec 18 18:05:41 EST 2003


Barnaby, after reading Alan'd reply, I think I missed what you wanted to 
do; you want a transparent way of having the print statement write to a 
buffer that can be printed out later, right?

The two ideas from my last message (StringIO and saving/restoring 
sys.stdout) can do this for you:

============
import StringIO
import sys

print "first line to stdout"
buf = StringIO.StringIO()
#save stdout, and point stdout to StringIO buffer
temp = sys.stdout
sys.stdout = buf

for i in range(1,11):
    print "Buffered line", i
    #these prints go to buf

#restore stdout
sys.stdout = temp
print "second line to stdout"

#now dump the StringIO
print buf.getvalue()
buf.close()
============

Run this, and you should see the "Buffered line" lines printed after the 
"second line to stdout"

-- 
Terry Carroll
Santa Clara, CA
carroll at tjc.com 




More information about the Tutor mailing list