[Tutor] carriage return on windows

Michael Janssen mi.janssen at gmail.com
Tue Feb 1 14:30:37 CET 2005

On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex <apple_py at biz-experts.net> wrote:

> I played around with this output issue and I love the way it works.
> Now, how do you do this in *nix? I tried the same approach and I get a
> blank line for 5 seconds (or whatever number of cycles you have on your
> example) and the a final line with the last value of the iterable.
> Do you happen to know how this in done?

you might want to flush stdout after printing to it. "print" will
cares for this only when not using that trailing comma. "flush" means
to write immedatly instead to wait for a fair amount of data.

import sys,time
for i in range(8):
    sys.stdout.write( "step: %s\r" % i) 
    # or: print "step: %s\r" % i,

There's still another possibilty using ansi control sequences. The
dirty way is to print (without trailing comma) and go back to previous

import time
for i in range(8):
    print "step: %s\033[A" % i
    # print subsystem has done stdout.flush

It's dirty cause the next line was already entered and thus is written
(as an empty line) and content of older "steps" will stay an screen,
when subsequents lines aren't long enough to overwrite them. Which
also applies to \r:

import sys,time
for i in range(8,0,-1):
    # printing 8**8, ..., 0**0 on line. Forget to overwrite
    sys.stdout.write( "step: %s\r" % (i**i))

Fixes are to add whitespace to the line. Stepping back with \033[D
fixes the empty newline issue (which is most often not worth the

import sys,time
for i in range(8,0,-1):
    # fixing output length to 30
    output = "%-30s" % "step: %s" % (i**i)
    length = len(output)
    # "print output," would be different, because of implizit spaces
    sys.stdout.write("\033[D"* (length))


More information about the Tutor mailing list