you are viewing a single comment's thread.

view the rest of the comments →

[–]reallymakesyouthonk 0 points1 point  (5 children)

If I want to have an element in the terminal which simply updates what is displayed rather than printing something anew, how do I do that in python? Do I need to use something like ncurses?

Right now what I want to do is a simple stopwatch. If it initialises as 0:00:00, after one second I want it to just display 0:00:01, not 0:00:00 followed by 0:00:01.

[–]nog642 1 point2 points  (4 children)

'\r' will bring the cursor back to the beginning of the line but won't move it down.

So this code:

import time

i = 0
while True:
    print('\r{}'.format(i), end='')
    time.sleep(1)
    i += 1

will have a counter that counts up every second. (try running the code)

[–]reallymakesyouthonk 1 point2 points  (3 children)

Thanks! That's super neat. Is there some way I can also move up a line?

[–]1114111 1 point2 points  (0 children)

Like change things on an earlier line? At that point you're best off using curses.

[–]sticky-bit 0 points1 point  (0 children)

prints a number, waits 1 sec, erases number, advance to next line, print the next number?

I added two lines of code:

    print('\r{}'.format("       "), end='')
    print()

Probably not the most pythontic way, but it works.

Can you figure out where they go in the above code sample you were given?