[Tutor] new print statement + time module

Mark Tolonen metolone+gmane at gmail.com
Sat Feb 28 08:53:04 CET 2009


"spir" <denis.spir at free.fr> wrote in message 
news:20090228081629.36a244b4 at o...
> Le Sat, 28 Feb 2009 06:34:07 +0200,
> George Wahid <geoterium at gmail.com> s'exprima ainsi:
>
>> I downloaded python 3.0.1 today and started experimenting with the new
>> print statement.
>>
>> >>>import time
>> >>>for l in 'the answer':
>> ...    print(l,end='')
>> ...    time.sleep(0.1)
>>
>> the code is supposed to print "the answer" with a 0.1 second long
>> pause between the letters. instead, it waits for 1 second (
>> 0.1*len("the answer") seconds ) and then prints "the answer". what am
>> I doing wrong ?
>
> Indeed, it does the same for me with python 2.5:
>
> from time import sleep
> for c in "1234567890":
> sleep(0.25)
> print c,
>
> I guess python underlying outputs are managed like a queue that is flushed 
> at certain points, eg whan a newline comes.
> Already noticed weird outputs messing up ordinary prints (~ sys.stdout) 
> and exceptions messages (sys.stderr). I'd like to know more about that.
>
>> both replacing print(l,end='') with print(l) or using the msvcrt
>> module instead of the print function work fine.
>
> The same with py2.5. Without the ',', all is fine. Maybe there is a trick 
> to force python printing ot in due time, but I have no idea, sorry.

stdout is line-buffered.  Here's the trick:

import time
import sys
for l in 'the answer':
    print(l,end='')
    sys.stdout.flush()
    time.sleep(0.1)

-Mark




More information about the Tutor mailing list