[Tutor] buffering print statement
Terry Carroll
carroll at tjc.com
Thu Dec 18 13:35:29 EST 2003
On Thu, 18 Dec 2003, Barnaby Scott wrote:
> Is there a simple way of redirecting the output of
> 'print' statements in a script, until such time as I
> actually want them sent to stdout, and they can all be
> sent at once?
>
> I guess I could create a file-like object and then use
> 'print >>' to it, but this is not what I am after
> ideally.
That's what I would do. StringIO is good for this:
------------------
#test1.py
import StringIO
buf = StringIO.StringIO()
for i in range(1,11):
print >>buf, "Buffered line", i
print "now processing line", i
#now dump the StringIO
print buf.getvalue()
buf.close()
------------------
>python test1.py
now processing line 1
now processing line 2
now processing line 3
now processing line 4
now processing line 5
now processing line 6
now processing line 7
now processing line 8
now processing line 9
now processing line 10
Buffered line 1
Buffered line 2
Buffered line 3
Buffered line 4
Buffered line 5
Buffered line 6
Buffered line 7
Buffered line 8
Buffered line 9
Buffered line 10
> Equally I know I could assign sys.stdout to my
> 'buffer', but I don't know how to reverse the process
> and get at the output when I want it!
I wouldn't take that approach, but if you want, there are two ways to get
it back.
First, if you know that no one else has messed with stdout, the normal
stdout is stored in sys.__stdout__. So you can do this:
--------------------
import sys
print "writing to normal stdout"
outfile=open("output.txt","w")
sys.stdout=outfile
print "writing to file"
outfile.close()
sys.stdout=sys.__stdout__
print "back to the normal stdout again."
--------------------
This does just what the code implies; you'll see the two lines "writing to
normal stdout" and "back to the normal stdout again" on the console, and
output.txt will contain the line "writing to file".
Another, more general, approach, if you think that another part of the
program or caller may have assigned stdout to something other than the
normal stdout is simply to save it and restore it:
-----------------------
import sys
print "writing to normal stdout"
outfile=open("output.txt","w")
temp_file_object = sys.stdout
sys.stdout=outfile
print "writing to file"
outfile.close()
sys.stdout=temp_file_object
print "back to the normal stdout again."
-----------------------
But I think StringIO is probably the way to go.
--
Terry Carroll
Santa Clara, CA
carroll at tjc.com
More information about the Tutor
mailing list