Python中的多种完成样式

2024-10-02 18:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在玩Python的^{}模块。我注意到的一个问题是缺少直接将键绑定到Python函数的支持。换句话说,readline的^{}没有绑定。在

我的目的是根据按下的键有不同的完成逻辑。例如,除了传统的制表符补全之外,我还想绑定C-<space>之类的东西,并使用不同的函数执行补全。或者,另一个例子,模仿ciscoshell并将?键绑定到带有说明的命令列表。在

在只绑定一个完成符的情况下,是否可以检索触发完成事件的密钥?在

谢谢。在


Tags: 模块函数命令目的列表readline事件情况
1条回答
网友
1楼 · 发布于 2024-10-02 18:16:33

在readline 6.2.4.1的基础上,我添加了一个新函数,在readline.c中向python传递变量rl_completion_invoking_key的值,并生成了自己的函数阅读线.so. 然后我可以根据complete()函数中的调用键来决定不同的行为。在

readline.c:
static PyObject *
get_completion_invoking_key(PyObject *self, PyObject *noarg)
{
    return PyInt_FromLong(rl_completion_invoking_key);
}

PyDoc_STRVAR(doc_get_completion_invoking_key,
"get_completion_invoking_key() -> int\n\
Get the invoking key of completion being attempted.");

static struct PyMethodDef readline_methods[] =
{
...
{"get_completion_invoking_key", get_completion_invoking_key,
 METH_NOARGS, doc_get_completion_invoking_key},
...
}

in your own code:
readline.parse_and_bind("tab: complete")    # invoking_key = 9
readline.parse_and_bind("space: complete")  # invoking_key = 32
readline.parse_and_bind("?: complete")      # invoking_key = 63

def complete(self, text, state):
    invoking_key = readline.get_completion_invoking_key()

相关问题 更多 >