【问题标题】:Is it possible to add arbitrary keybindings to the Python interpreter?是否可以向 Python 解释器添加任意键绑定?
【发布时间】:2012-07-27 01:38:05
【问题描述】:

在python解释器中我们可以使用

readline.parse_and_bind('tab: complete')

启用标签补全

是否可以将任意键绑定到我们自己的函数?
我想分别将 CTRL+E 和 CTRL+SHIFT+E 绑定到 edit_history() 和 edit_history(True) ,其中 edit_history() 是我自己在 .pythonrc 中定义的函数

def edit_history(fork=False):
    import readline
    timeStamp = time.strftime("%Y%m%d-%H%M%S")
    tmpFile = '/tmp/pyHistory.%s' % timeStamp
    readline.write_history_file(tmpFile)
    if not fork:
        os.system('gvim -f %s' % tmpFile)
        readline.clear_history()
        readline.read_history_file(tmpFile)
        os.unlink(tmpFile)
    else:
        os.system('gvim %s' % tmpFile)

任何指针将不胜感激

谢谢,
墙裙

【问题讨论】:

  • 你应该看看像iPython这样的增强型解释器,它有很多有趣的%magic
  • 感谢 Paulo 的建议,但我无法习惯 iPython。

标签: keyboard-shortcuts interpreter key-bindings python


【解决方案1】:

是的……有点。定义 edit_history 函数后,您可以将键映射到序列“edit_history()\n”。按该键将模拟键入“edit_history”,然后按 Enter 键。

【讨论】:

  • 啊,我试过不带 ()\n,因为完整的绑定不包括那个。但我不确定如何指定密钥。您有 F2 或 CTRL+E 的示例吗?谢谢!
  • 我设法让它与 readline.parse_and_bind('C-e: "edit_history()\n"') 无法结合使用 Meta 或 Shift。我可能需要一个完全独立的绑定。感谢 chepner 为我指明了正确的方向。
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2021-08-29
  • 2020-01-17
  • 2022-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多