[Tutor] Writing to the terminal?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Mon Dec 13 19:11:40 CET 2010

Op 2010-12-12 22:33, Steven D'Aprano schreef:
> Terry Carroll wrote:
>> import time
>> for t in range(10,0, -1):
>>     print "%s \x0D" %t,
>>     time.sleep(1)
>> print # get to next line
>> print "Done!"
> Which operating system and terminal did you use?
> In my experience, using print is not satisfactory, because the print 
> command buffers the output and doesn't actually print anything until 
> either a newline or you have a certain number of characters. So the 
> above will queue up the following string:
> "10 \r9 \r8 \r7 \r6 \r5 \r4 \r3 \r2 \r1 \r\n"
> before anything becomes visible, and of course that just looks like "1".

Instead of print, use sys.stdout.write():

import sys
import time
for t in range(10, 0, -1):
  sys.stdout.write('\r%s ' % t)

The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven

More information about the Tutor mailing list