views:

182

answers:

4

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.

A: 

When I do this in shell scripts on Unix, I tend to just use the clear program. You can use the Python subprocess module to execute it. It will at least get you what you're looking for quickly.

Omnifarious
A: 
[ignacio@localhost ~]$ ldd /usr/bin/top | grep curses
        libncursesw.so.5 => /lib64/libncursesw.so.5 (0x0000003ae1400000)

curses it is.

Ignacio Vazquez-Abrams
+1  A: 

Sounds like a job for curses. It is the most commonly used library for text-mode screen layout and management. Python has very good support for curses, including support for panels:

gavinb
+2  A: 

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.

Torsten Marek