[Tutor] "Print" behaviour inside a loop?

Max Noel maxnoel_fr at yahoo.fr
Sun Jun 12 01:50:40 CEST 2005


On Jun 12, 2005, at 00:42, Simon Gerber wrote:

> Any hints? I looked up the python reference manual, but couldn't find
> any way to force print statements to draw. Should I be looking into
> threads, perhaps?

     I/O in Python is buffered -- that is, it uses RAM whenever  
possible to delay the actual reading/writing operations, which in  
turn speeds them up. For example, when you read a character from a  
file, a larger part of the file is stored in a RAM buffer so as to  
speed up subsequent calls.
     In the same way, whenever you write to stdout (or to a file),  
everything is stored in a buffer until a newline is reached or the  
buffer is manually flushed. The latter is what you're looking for,  
it's done by calling the file object's (in your case, stdout --  
remember, on UNIX everything is a file) flush method.
     Here's a small example:

#!/usr/bin/env python
import time, sys

for i in xrange(20):
     sys.stdout.write(".")
     sys.stdout.flush()
     time.sleep(0.2)


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"



More information about the Tutor mailing list