Welcome, guest | Sign In | My Account | Store | Cart

With this function you can overwrite what you printed in the console, remaining in the same line. It's specially useful when you want to show information and update it regularly.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import msvcrt
import time

def PrintStatic(Value, Prefix=''):
    ValStr = Prefix + `Value`
    map(lambda x:msvcrt.putch(x),ValStr + len(ValStr) * '\x08')

for i in range(50):
    PrintStatic(i, '        ')
    time.sleep(0.1)
PrintStatic('Completed.')
 

You can use a prefix that will be added to the representation of the value.

Don't forget the values are not erased, only overwrited, so if your last data is longer than the new one, maybe you'll need to overwrite it with spaces before print the value that result shorter string.

It only works in Windows platform. (In Linux,Unix you have curses readily available).

4 comments

Tobias Klausmann 19 years, 3 months ago  # | flag

alternatives. Why not use sys.stdout.write() or my printf-lambda with control characters?

Dirk Holtwick 19 years, 3 months ago  # | flag

simpler. Why so complicated?

import sys
import time

def status(s):
    sys.stdout.write(s + " " * (78 - len(s)) + "\r")

for i in range(12):
    status(str(12-i))
    time.sleep(1)
status("done")
Armando Baratti (author) 19 years, 3 months ago  # | flag

better. You´re right, I was a bit precipitate. You could even put the 'str()' cast inside the function so you need not to do it in every call. (And this way it would be conceptually more correct ;).

import sys
import time

def status(obj):
    s = str(obj)
    sys.stdout.write(s + " " * (78 - len(s)) + "\r")

for i in range(12):
    status(12-i)
    time.sleep(1)

for i in range(8):
    status(range(8-i))
    time.sleep(1)

status("done")
Dan Kruger 18 years, 1 month ago  # | flag

This Version is platform-independent... def PrintStatic(a_string=''):

 print '\b%s%s'%(a_string,'\b' * len(a_string)),