无论我做什么,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']
。如何强制保留我的订单?
答案 0 :(得分:0)
有专门的选项: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
可移植性超出了本答案的范围。