paulgorman.org

Python & Curses

curses is a library for manipulating terminal displays. It was originally developed to support the game rogue on early BSD Unix, but is now widely used to provide an interface for a variety of tools (installers, system conguration, etc.) on Linux and many unix-like platforms. (The original curses has been supplanted by ncurses, which started as a free clone of curses but has become the de-facto extended standard.)

The basic curses unit is the window. Windows which are as large as the entire terminal display are called screens. By default, curses creates two windows/screens: curscr and stdscr. curscr contains the actual current contents of the terminal. stdscr is like an off-screen draw buffer that includes what will be flushed to curscr as soon as we call refresh(). We never really want to touch curscr directly.

Note: when using coordinates, curses orders them as y, x (i.e. high, wide) rather than the more typical x, y.

Minimal Python Curses Example

#!/usr/bin/env python

import curses
import time

def centerStringInWindow(window, string):
    height, width = window.getmaxyx()
    yorigin = (height / 2) - 1
    xorigin = (width / 2) - (len(string) / 2)
    window.addstr(yorigin, xorigin, string)
    return

def main(stdscr):
    stdscr.clear()
    hello = 'Hello, world!'
    bye = 'Goodbye.'
    stdscr.addstr(hello)
    stdscr.refresh()
    while 1:
        c = stdscr.getch()
        if c == ord('q'):
            stdscr.clear()
            centerStringInWindow(stdscr, bye)
            stdscr.refresh()
            time.sleep(2)
            break
        elif c == ord('h'):
            helpMessage = 'Press "q" to quit.'
            centerStringInWindow(stdscr, helpMessage)
            stdscr.refresh()

if __name__ == '__main__':
    # curses.wrapper takes care of terminal initialization and cleanup for us:
    curses.wrapper(main)

References