【问题标题】:ipython: change PageDown/PageUp to move back/forward through command historyipython:更改 PageDown/PageUp 以通过命令历史记录向后/向前移动
【发布时间】:2021-01-27 11:53:25
【问题描述】:

在我的 shell (zsh) 或 python 中,我可以通过按 PageDown 向后查看命令历史记录,并且可以通过按 PageUp 前进.

但是在ipython 中,这些快捷键是相反的。

ipython 定义的这些快捷方式在哪里,如何将它们反转回来,以便

PageDown历史回溯,PageUp历史前进?

我在 Debian 10 上使用 ipython3 版本 5.8.0

【问题讨论】:

  • 你是什么python版本。
  • @Chandan - python 3.7.3
  • 你的操作系统是什么?
  • Debian 10 @Chandan
  • 尝试在ipythonrc 文件中添加这些绑定 - readline_parse_and_bind "\e[5~": history-search-backward, readline_parse_and_bind "\e[6~": history-search-forward

标签: python ipython prompt-toolkit


【解决方案1】:

~/.ipython/profile_default/startup 目录中创建任何名称以扩展名.py.ipy 结尾的脚本

例如我创建了history_keybindings.py 并将其放在~/.ipython/profile_default/startup 目录中

from IPython import get_ipython
from IPython.terminal.shortcuts import previous_history_or_previous_completion, next_history_or_next_completion
from prompt_toolkit.keys import Keys
from prompt_toolkit.filters import HasSelection

ip = get_ipython()

registry = None

if (getattr(ip, 'pt_app', None)):
   # for IPython versions 7.x
   registry = ip.pt_app.key_bindings
elif (getattr(ip, 'pt_cli', None)):
   # for IPython versions 5.x
   registry = ip.pt_cli.application.key_bindings_registry

if registry:
   registry.add_binding(Keys.PageUp, filter=(~HasSelection()))(previous_history_or_previous_completion)
   registry.add_binding(Keys.PageDown, filter=(~HasSelection()))(next_history_or_next_completion)

注意:更多信息请查看here

【讨论】:

  • 还是不行:AttributeError: 'CommandLineInterface' object has no attribute 'key_bindings'
  • @400theCat 我已经更新了答案,请再次查看
【解决方案2】:

在 IPython 5.x 版中,文档中提到了这一点:Specific config details — IPython 5.11.0.dev documentation

要获取要绑定的函数,请参阅key_binding/bindings/basic.py:默认为

handle("pageup", filter=~has_selection)(get_by_name("previous-history"))
handle("pagedown", filter=~has_selection)(get_by_name("next-history"))

所以,把这段代码放在startup file

from IPython import get_ipython
from prompt_toolkit.filters import HasSelection
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.bindings.named_commands import get_by_name

registry = get_ipython().pt_cli.application.key_bindings_registry
registry.add_binding(Keys.PageUp, filter=~HasSelection())(get_by_name("next-history"))
registry.add_binding(Keys.PageDown, filter=~HasSelection())(get_by_name("previous-history"))

在较新的 IPython 版本(例如 7.19.0)上,将 registry = ... 行替换为

registry = get_ipython().pt_app.key_bindings

参考:Specific config details — IPython 7.19.0 documentation

【讨论】:

  • 可能相关:12345
  • 我收到此错误:AttributeError: 'TerminalInteractiveShell' object has no attribute 'pt_app'
猜你喜欢
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 2013-06-12
  • 2016-05-07
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多