Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to change text after it's printed?

Tags:

python

I have a Python program I am writing and I want it to be able to change text after it is printed. For example, let's say I want to print "hello" and erase one letter every second. How would I go about doing that?

Also, I heard about curses but I can't get that to work, and I do not want to simply create new lines until the old text is off the screen.

like image 256
futurevilla216 Avatar asked Mar 24 '11 22:03

futurevilla216


2 Answers

Here's one way to do it.

print 'hello',
sys.stdout.flush()
...
print '\rhell ',
sys.stdout.flush()
...
print '\rhel ',
sys.stdout.flush()

You can probably also get clever with ANSI escapes. Something like

sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
    time.sleep(1)
    sys.stdout.write('\033[D \033[D')
    sys.stdout.flush()
like image 72
Marcelo Cantos Avatar answered Oct 16 '22 07:10

Marcelo Cantos


For multi-line output, you can also clear the screen each time and reprint the entire thing:

from time import sleep
import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

message = 'hello'
for i in range(len(message), 0, -1):
    cls()
    print message[:i]
    sleep(1)
like image 25
endolith Avatar answered Oct 16 '22 06:10

endolith