Recursion Recursion - 5 months ago 85
Python Question

Dynamic terminal printing with python

Certain applications like hellanzb have a way of printing to the terminal with the appearance of dynamically refreshing data, kind of like top().

Whats the best method in python for doing this? I have read up on logging and curses, but don't know what to use. I am creating a reimplementation of top. If you have any other suggestions I am open to them as well.

Answer

The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use '\r' (carriage return) and sys.stdout:

import sys
import time

for i in range(10):
    sys.stdout.write("\r{0}>".format("="*i))
    sys.stdout.flush()
    time.sleep(0.5)

If you need a proper console UI that support moving the pointer etc., use the curses module from the standard library:

import time
import curses

def pbar(window):
    for i in range(10):
        window.addstr(10, 10, "[" + ("=" * i) + ">" + (" " * (10 - i )) + "]")
        window.refresh()
        time.sleep(0.5)

curses.wrapper(pbar)

It's highly advisable to use the curses.wrapper function to call your main function, it will take care of cleaning up the terminal in case of an error, so it won't be in an unusable state afterwards.

If you create a more complex UI, you can create multiple windows for different parts of the screen, text input boxes and mouse support.