Friday, July 27, 2007

Tool for checking key events with curses

I'm doing a bit of curses programming at the moment. I've made a tool to check the keys entered are as expected. Do what you like with it.


#!/usr/bin/evn python
import curses
import curses.ascii

keys = {}
for name in dir(curses):
    if name.startswith('KEY_'):
        keys[getattr(curses, name)] = name

for name in dir(curses.ascii):
  if name.isupper():
    keys[getattr(curses.ascii, name)] = name

for i in xrange(128):
    if curses.ascii.isprint(i):
        keys[i] = "'%s'" % chr(i)

s = curses.initscr()
s.keypad(1)
curses.noecho()
try:
    while True:
        c = s.getch()
        s.clear()
        try:
            key = keys[c]
        except KeyError:
            key = '%d' % c
        s.addstr("Key = %s" % key)
        s.refresh()
except:
    curses.endwin()
Post a Comment