【问题标题】:Adding a key binding on python prompt-toolkit-3.0.2 breaks the suggestion and history search在 python prompt-toolkit-3.0.2 上添加键绑定会破坏建议和历史搜索
【发布时间】:2020-01-10 04:08:27
【问题描述】:

我正在尝试添加一种不同的方式来完成多行输入。应该很简单,但我得到了一个意想不到的结果:添加新绑定后,历史记录和建议功能停止工作。

我尝试使用 load_basic_bindings 但没有帮助。

如果我对键绑定、建议和历史工作再次发表评论。

from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.key_binding import KeyBindings

session = PromptSession()

# load empty binds
bindings = KeyBindings()

# reading from the basic binds did not work either
# bindings = load_basic_bindings()

# HERE IS THE PROBLEM
# After adding this the history and suggest stop working
# should just add a new way to exit
# I have tested with the eager True and False, with no changes
@bindings.add('#')
def _(event):
    event.app.exit(result=event.app.current_buffer.text)

while True:
    text = session.prompt(
        '> ',
        auto_suggest=AutoSuggestFromHistory(),
        key_bindings=bindings,     # if I comment the key bindings, the history and search work againg
        multiline=True,            # this bug just happens on multiline, if put this False the bug does not happens
        enable_history_search=True
    )
    print('You said: %s' % text)

【问题讨论】:

  • 当我使用load_basic_bindings() 运行所有代码并使用alt+Enter 时,它会添加到历史记录中——我可以使用#,但它不会添加到历史记录中。看来您必须在 # 中添加功能,将其添加到历史记录中。

标签: python prompt-toolkit


【解决方案1】:

如果我使用load_basic_bindings(),我可以使用Alt+Enter 接受命令并将其添加到历史记录中。
对于#,我必须添加将命令添加到历史记录的函数

session.history.append_string(event.app.current_buffer.text)

我可以使用箭头从历史记录中进行选择。它显示了历史的建议。

在 Linux Mint 19.2(基于 Ubuntu 18.04)、Python 3.7.6、Prompt Toolkit 3.0.2 上测试


from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings.basic import load_basic_bindings

session = PromptSession()

# load empty binds
#bindings = KeyBindings()

# reading from the basic binds did not work either
bindings = load_basic_bindings()

# HERE IS THE PROBLEM
# After adding this the history and suggest stop working
# should just add a new way to exit
# I have tested with the eager True and False, with no changes
@bindings.add('#')
def _(event):
    session.history.append_string(event.app.current_buffer.text)
    event.app.exit(result=event.app.current_buffer.text)

while True:
    text = session.prompt(
        '> ',
        auto_suggest=AutoSuggestFromHistory(),
        key_bindings=bindings,     # if I comment the key bindings, the history and search work againg
        multiline=True,            # this bug just happens on multiline, if put this False the bug does not happens
        enable_history_search=True
    )
    print('You said: %s' % text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多