我想在基于 curses 的 python 程序中提供键绑定(bind)。理想的解决方案是在 getch()
周围有一个抽象层,它产生可读的字符串,可能是类似 vim 的格式。
在 python 中:
def get_keycomb(wind):
string = read_keycomb(wind) # read with wind.getch() as needed
return string # something like '<C-S-a>'
然后我可以通过将字符串用作 dict
函数中的键来轻松实现映射。
是否有提供此类功能的 Python 库,或者比手动为所有内容提供名称更简单的实现方法?
最佳答案
所有非特殊键的代码都是字符的ascii码,所以这部分表很容易建。
char_codes = {chr(i):i for i in range(256)}
所有特殊字母的代码在 curses 模块中作为 KEY_* 常量可用,所以我们可以通过这种方式获得它们:
specials_codes = {name[4:]: value for name, value in vars(curses).items()
if name.startswith('KEY_')}
因此您可以使用此代码构建映射:
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)
关于Python:将关键代码诅咒为可读(类似 vim?)的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769133/