【问题标题】:Python + GNU/readline bindings: keep my sort orderPython + GNU/readline 绑定:保持我的排序顺序
【发布时间】:2015-09-22 15:31:59
【问题描述】:

无论我做什么,GNU/readline 似乎都会对我的数据进行排序。我的代码看起来就像文档中的一样:

tags = [tag.lower() for tag in tags]
def completer(text, state):
    text = text.lower()
    options = [tag for tag in tags if tag.startswith(text)]
    try:
        return options[state]
    except IndexError:
        return None

readline.set_completer(completer)
readline.parse_and_bind('tab: menu-complete')

如果我的标签是['jarre', 'abba', 'beatles'],我会不断收到['abba', 'beatles', 'jarre']。如何强制保留我的订单?

【问题讨论】:

    标签: python readline libreadline


    【解决方案1】:

    对此有专门的选项:rl_sort_completion_matches。它按字典顺序对选项进行排序,并删除重复项 - 因此,如果您覆盖它,您需要自己处理重复项。

    但是,它不能从 Python 的绑定中访问。

    幸运的是,这并不意味着您无法使用它 - 您可以使用 cdll 或 ctypes 进行更改。由于它是一个全局变量而不是一个函数,我将使用in_dll 方法:

    import ctypes
    rl = ctypes.cdll.LoadLibrary('libreadline.so')
    sort = ctypes.c_ulong.in_dll(rl, 'rl_sort_completion_matches')
    sort.value = 0
    

    在此之后,应该以正确的顺序检索匹配项。

    不幸的是,这不是一个非常便携的方法 - 例如,在 Windows 中,您应该使用 .dll 后缀,而不是 Linux 的 .so。但是,关注ctypes 的可移植性超出了此答案的范围。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2023-01-07
      • 1970-01-01
      • 2010-10-06
      • 2012-10-01
      相关资源
      最近更新 更多