View Single Post
Old Dec 11th, 2005, 8:59 AM   #27
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
Yeah. If you know how many characters wide your terminal is (you can find this by reading the output of `tput cols` on *nix) you can have you can easily clear the current line and write new text to it. So for example (untested):
import time, sys
# Get the amount of characters wide the terminal is. 
# On *nix you can do: int(os.popen("tput cols").read().strip())
width = getTerminalWidth()
message1 = "Message number 1"
# Print message1 to the terminal, padded to the end of the line with spaces. 
# If we pad the output then we know how many backspaces characters
# we need to write out to clear the whole line. width - len(message1) will
# give us the amount of space characters we need.
sys.stdout.write(message1 + " " * (width - len(message1)))
# Flush the text we've written to stdout. If Python doesn't see a newline
# it doesn't flush for you.
sys.stdout.flush()
# Pause execution for a second...
time.sleep(1)
# Now clear the line
sys.stdout.write("\b" * width)
# And write a new message
sys.stdout.write("Message number 2...\n")
I used this technique to make a command-line progress bar, for example.
Cerulean is offline   Reply With Quote