我正在尝试停用 readline使用后自动完成。因此我想写一个这样的装饰器:
#!python
from contextlib import contextmanager
import readline
def main():
with readline_autocompletion():
raw_input('first: ')
raw_input('second: ')
@contextmanager
def readline_autocompletion():
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(' \t\n')
readline.set_completer(None)
yield
# How to unload autocompletion without this hack??
readline.set_completer(no_complete)
def no_complete(text,state):
return None
if __name__ == '__main__':
main()
如何为第二个 raw_input()
再次停用 readline 自动完成?
编辑
我现在设法通过设置一个只返回 None
的完成器来停用完成(参见上面的代码)。这真的是要再次停用自动完成功能的方法吗?感觉像黑客。
最佳答案
在调用 readline.parse_and_bind('tab: complete')
之后,TAB 被映射到执行完成的函数上。如果未设置自定义完成器,则使用默认系统文件完成。有比定义自定义 stub 函数来更改完成行为更好的解决方案。
TAB键可以像以前一样插入self(TAB符号)'tab: complete'
绑定(bind):
readline.parse_and_bind('tab: self-insert')
有关详细信息,请考虑 python readline 模块基于 GNU Readline 库 (in case of OS X it may be libedit
)。因此,库的文档可以解释函数 parse_and_bind
。这里最有趣的部分是"Readline Init File" .函数 parse_and_bind
将其输入字符串作为 Readline Init File 传递。
可以设置各种变量的值或将不同的功能绑定(bind)到键上。
例如,disable-completion
变量应该作为'tab: self-insert'
:
If set to
On
, Readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert. The default isoff
.
然而,这并不完全正确。在当前的库源码(readline-6.3)中可以看到。如果变量 disable-completion
设置为 on
complete
函数(绑定(bind)到 tab
)总是插入符号按下的键。但是,self-insert
仅在 insert
模式下插入符号。在 overwrite
模式下,它会覆盖光标位置的符号。例如,绑定(bind)到 Ctrl-a
键,函数切换覆盖模式,set disable-completion on
并保持 complete
绑定(bind)到 tab
:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set disable-completion on')
readline.parse_and_bind('C-a: overwrite-mode')
起初,tab 键与 'tab: self-insert'
一起工作。然而,在按下 Ctrl-a
后,覆盖模式被启用。现在 tab 键仍然插入 tab 符号,但在 self-insert
的情况下,tab 键会覆盖符号。
关于python - 停用 readline 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33038056/