Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I edit a string that was printed to stdout?

How can I edit a string that I just printed? For example, for a countdown counter (First prints 30, then changes it to 29 and so on)

Thanks.

like image 260
Alex Avatar asked Mar 30 '11 20:03

Alex


2 Answers

Print a carriage return \r and it will take the cursor back to the beginning on the line. Ensure you don't print a newline \n at the end, because you can't backtrack lines. This means you have have to do something like:

import time
import sys
sys.stdout.write('29 seconds remaining')
time.sleep(1)
sys.stdout.write('\r28 seconds remaining')

(As opposed to using print, which does add a newline to the end of what it writes to stdout.)

like image 99
bradley.ayers Avatar answered Sep 28 '22 02:09

bradley.ayers


If you're targeting Unix/Linux then "curses" makes writing console programs really easy. It handles color, cursor positioning etc. Check out the python wrapper: http://docs.python.org/library/curses.html

like image 20
das_weezul Avatar answered Sep 28 '22 00:09

das_weezul