Michael Janssen wrote:

On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex <[EMAIL PROTECTED]> 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,
sys.stdout.flush()
time.sleep(.5)



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

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

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))
   sys.stdout.flush()
   time.sleep(.5)

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
effort):

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


regards Michael




Excellent. Thanks Kent and Michael.

Great tutorial ;-)

You're right Michael. This last one works nicely but it is probably not worth the effort.

I likes the previous one but adding fixed formatting to the number output, something like
"step: %9s\r"


instead of just

"step: %s\r".

Thanks again.
Victor

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to