Python: CUI application with curses

This article will describe usage of curses library.

1 import

Import curses.

import curses

2 Initialize

  • Initialize curses with curses.initscr(), and get screen handler object.
  • Disable echo by keyboard input with curses.noecho().
stdscr = curses.initscr()
curses.noecho()

3 Draw

  • Clear screen with stdscr.clear().
  • Add string to screen with stdscr.addscr(). You need to call stdscr.addscr() multiple time for drawing multiple strings before calling stdscr.clear().
  • Draw screen with stdscr.clear().
stdscr.clear()
stdscr.addstr(y, x, string)
stdscr.refresh()
time.sleep(1)

4 Finalize

Finalization must be done even if exception happens. If finalization is not done, terminal console will be collapsed. You need to run "stty sane" for fixing it.

  • Enable echo by keyboard input with curses.echo().
  • Finalize curses with curses.endwin().
curses.echo()
curses.endwin()

5 Sample code

Sample code draws string on every seconds until after 10 seconds. This can be interrupted by Ctrl + C.

#!/usr/bin/env python

import curses
import time

if __name__ == "__main__":
    try:
        stdscr = curses.initscr()
        curses.noecho()

        for t in range(0, 10):
            stdscr.clear()
            stdscr.addstr(
                0, 0, 'Program will be terminated after %s seconds' % (10 - t))
            stdscr.refresh()
            time.sleep(1)
    except:
        # Exception by Ctrl + C
        pass
    finally:
        curses.echo()
        curses.endwin()