[Tutor] different behaviour in Idle shell vs Mac terminal

Peter Otten __peter__ at web.de
Mon Jan 9 10:05:47 CET 2012


Alan Gauld wrote:

> On 08/01/12 23:34, Adam Gold wrote:
>>
>> I have short piece of code I'm using to print a string to
>  > the terminal one letter at a time.  It works fine when
>> I invoke the script from within Idle; each letter appears
>> afterthe preceding one according to the designated time
>  > interval.
>  > However if I run it in the Mac terminal
>  > ('python3 ./script.py'),
>  > there's a pause and then the whole string prints in one go.
> 
> Thats because you are writing to stdout rather than using print
> The output is buffered and the terminal prints the output after the
> bufrfer is flushed, which happens at the end of the program
> (probably when the file object is auto closed). if you use print
> that shouldn't happen.
> 
> The alternative is to explicitly flush() the file after each write.
> 
>> import sys
>> import time
>>
>> text = "this text is printing one letter at a time..."
>> for char in text:
>>      sys.stdout.write(char)
> 
> either use
>         print char,    # comma suppresses \n

The newline will be suppressed, but the next print statement will inject a 
space before dumping its arguments. Also, you still need to flush(). That 
makes a working print-based solution a bit esoteric:

for c in text:
    print c,
    sys.stdout.softspace = False
    sys.stdout.flush()
    time.sleep(.3)




More information about the Tutor mailing list