15

I want to provide keybindings in a curses-based python program. The ideal solution would be to have an abstraction layer around getch() that yields readable strings, maybe in a vim-like format.

In pythonese:

def get_keycomb(wind):
    string = read_keycomb(wind) # read with wind.getch() as needed
    return string # something like '<C-S-a>'

Then I could easily implement mappings by using the strings as keys in a dict function.

Is there a python library that provides this sort of functionality, or an easier way to achieve it than manually providing names for everything?

Pravitha V
  • 3,308
  • 4
  • 33
  • 51
salezica
  • 74,081
  • 25
  • 105
  • 166
  • 1
    I remember looking at the code for the [bypthon project](https://bitbucket.org/bobf/bpython) and thinking that they had a pretty good system for dealing with keys, they use curses and it might be worth checking the project out. Great question though, wish I had a better answer. I would love to see a library for this as well. – Nolen Royalty May 26 '12 at 20:38

2 Answers2

5

The codes for all the non-specials keys are the ascii codes of the characters, so that part of the table is easy to build.

char_codes = {chr(i):i for i in range(256)}

The codes for all the specials letters are available in the curses modules as KEY_* constants, so we can get them all this way :

specials_codes = {name[4:]: value for name, value in vars(curses).items()
    if name.startswith('KEY_')}

So you can build you mapping with this code :

import curses

mapping = {chr(i):i for i in range(256)}
mapping.update((name[4:], value) for name, value in vars(curses).items()
    if name.startswith('KEY_'))

print(mapping)
madjar
  • 12,691
  • 2
  • 44
  • 52
1

Rather than using curses for input, if you use libtermkey then it provides easy functions for converting key structures to and from human-readable strings, in just this form. Specifically the functions termkey_strfkey and termkey_strpkey.

http://www.leonerd.org.uk/code/libtermkey/doc/termkey_strfkey.3.html

http://www.leonerd.org.uk/code/libtermkey/doc/termkey_strpkey.3.html

This is a C library, but it does have a Python binding; see

https://github.com/temoto/ctypes_libtermkey

LeoNerd
  • 8,344
  • 1
  • 29
  • 36