【问题标题】:How to get the invoking_key of complete function with readline?如何用readline获取完整函数的invoking_key?
【发布时间】:2017-05-21 11:09:24
【问题描述】:

我是编码新手,一直在研究具有自动完成功能的 cisco os 风格的命令行界面。看来python的内置模块readline是我可行的选择。 我打算按下“TAB”、“空格”和“?”的按键。以稍微不同的行为实现完成,但只支持绑定一个完整的函数,我不确定是否有办法获取哪个键刚刚调用了这个函数。或者我应该为此寻找其他选择吗? 任何提示将不胜感激!

【问题讨论】:

  • 您要在什么环境中添加自动完成功能? Python交互式shell?编辑?实际系统外壳?其中大部分已经自动完成。
  • 我正在尝试在 linux 服务器(使用 python 2.x)上构建我自己的命令行界面,它可以像 cisco 交换机/路由器一样自动完成预先设计的基于数据的参数.例如Rt# config (press-enter) Rt>config# interface (press-enter) Rt>config>interface# para1 para2 ... @DanFarrell
  • 我会研究这个,提前感谢@DanFarrell
  • 不幸的是这不是我要找的:-(

标签: python autocomplete readline


【解决方案1】:

在readline 6.2.4.1的基础上,我在readline.c中增加了一个新函数,将变量rl_completion_invoking_key的值传递给python,并生成了我自己的readline.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 my 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()

【讨论】:

    猜你喜欢
    • 2022-10-02
    • 1970-01-01
    • 2022-08-13
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2023-03-03
    相关资源
    最近更新 更多