PDA

View Full Version : Python : How to control print location in terminal ??!!



Ahmedmb
June 16th, 2009, 10:01 PM
:p Hi All

i need to print countdown timer but i need it to print in same line
not like this:
01:22
01:21
01:20

how i move the cursor and print in same location >??
:) THX

Can+~
June 16th, 2009, 10:14 PM
Easiest way?
http://en.wikipedia.org/wiki/Carriage_return


print "I hate carriage return\rI love",

Use the "," to avoid the python automatic newline.

Or if you already jumped into python3:


print("I hate carriage return\rI love", end="")

unutbu
June 16th, 2009, 10:29 PM
#!/usr/bin/env python
from time import sleep
import sys
for x in range(10):
print '\r%s'%x,
sys.stdout.flush()
sleep(1)

You'll need to flush the output too...

fr4nko
June 16th, 2009, 10:32 PM
The '\r' tip is a good one. Just for information, if you want a full control of your terminal display you can use the curses (http://docs.python.org/howto/curses.html) module.

Can+~
June 16th, 2009, 10:34 PM
Pair it with string multiplication to create a loading bar:


#!/usr/bin/env python
from time import sleep
import sys

for x in range(100):
print '\rDownloading: %s (%d%%)' % ("|"*(x/2), x),
sys.stdout.flush()
sleep(0.1)

(Remember that "hello "*3 = "hello hello hello ")

Ahmedmb
June 17th, 2009, 02:09 PM
THX All :p