You should use what your terminal provides. In most cases you need to use '\r'
(carriage return, return to first column in that line); but depending on the operating system this might be interpreted such that it also appends a line feed. I feel I remember that OSX might do this.
Also you need to avoid the automatic newline print
will always append. You could use a trailing comma for this, but this has issues (stray space, no flushing). So I propose to use sys.stdout.write()
instead and because without a newline typically no flushing will be done, you should use sys.stdout.flush()
explicitly as well.
Then, returning to the first column will not delete the old output, so it only gets overwritten by the next line. If that is shorter than the one before, you will have trailing junk. To avoid this, again use what your terminal provides (very often '\x1b[K'
erases everything till the end of the line without moving the cursor, but if this does not work for you, just print some spaces or make sure your output is formatted always to the same width).
EL = '\x1b[K' # clear to end of line
CR = '\r' # carriage return
sys.stdout.write(("%d hours %d minutes %s seconds" + EL + CR) % (h, m, s))
sys.stdout.flush()
A more decent approach (besides this shortcut by using literal sequences) is to use the official curses library.
import curses
curses.setupterm()
EL = curses.tigetstr('el')
CR = curses.tigetstr('cr')
And if CR really does not work on OSX as we want it to, then there might be goto in your termcaps to go to a specific position (e. g. first column) or you can use save_cursor
(SC) and restore_cursor
(RC) to restore an earlier saved position:
sys.stdout.write(SC + "%d hours %d minutes %s seconds" + EL + RC % (h, m, s))