The following codes works in Python 2 and Python 3.
But for Python 3, see the good answer of Ramchandra Apte.
from sys import stdout
from time import sleep
for i in xrange(5,0,-1):
stdout.write(str(i))
sleep(1)
stdout.write(' Blastoff')
The str(i)
is necessary in order thatthis code executes in a command line window. In an EDIT shell window , it can be written stdout.write(i)
but the '\b'
signal doesn't move the cursor back, it appears a square in place of it.
.
By the way, try the following code to see what happens.
The '\b'
triggers the cursor to move back of one position, replacing the preceding character, so each character is written just at the place of the one the preceded it in time. That works only in a command line window, not in an EDIT shell window.
from sys import stdout
from time import sleep
for i in xrange(5,0,-1):
stdout.write(str(i))
sleep(1)
stdout.write('\b')
stdout.write('Blastoff')
raw_input('\n\npause')
Complexifying (still to execute in a command line window):
from sys import stdout
from time import sleep
tu = (' End in 24 seconds',
' It remains 20 seconds',
' Still only 16 seconds',
' Do you realize ? : 12 seconds left !',
' !!!! Hey ONLY 8 seconds !!')
for s in tu:
stdout.write('*')
sleep(1)
stdout.write(s)
sleep(2)
stdout.write(len(s)*'\b' + len(s)*' ' + len(s)*'\b')
sleep(1)
stdout.write(len(tu)*'\b' + len(tu)*'!' + ' ')
n = 4
for x in xrange(n,0,-1):
stdout.write('\b!'+str(x))
sleep(1)
stdout.write(len(tu)*'\b' + n*'\b' + '\b')
stdout.write(' # !! BLASTOUT !! #\n')
sleep(0.8)
stdout.write(' ## !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write(' ### !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write(' #### !! BLASTOUT !! ####\n')
sleep(3)