【问题标题】:ipython shell - how to emulate an enter pressipython shell - 如何模拟输入压力
【发布时间】:2021-05-31 16:54:35
【问题描述】:

我想退出 ipython shell,即输入 %exit 然后回车,当按下转义键时。我可以在 shell 中成功键入“%escape”,但很难弄清楚“enter”按。

参考:https://ipython.readthedocs.io/en/latest/config/details.html#keyboard-shortcuts

启动文件夹中的 .py 文件中的代码:

from prompt_toolkit.key_binding import KeyBindings
from IPython import get_ipython
ip = get_ipython()

def exit_ipy(event):
    buffer = event.current_buffer
    buffer.insert_text('%exit') # just need to figure out how to insert an "enter" press after
    buffer.accept_action.validate_and_handle(event.cli, buffer) # I thoght this may work?

ip = get_ipython()
registry = ip.pt_app.key_bindings
registry.add_binding(u'escape')(exit_ipy)

【问题讨论】:

  • 愚蠢的评论:您是否尝试在“%exit”之后添加一个“\n”?比如buffer.insert_text('%exit\n')
  • 我做了,这会产生换行符。也试过\r
  • 问题是,您希望控制流退出到哪里?退出整个 Python 解释器?在某个时候返回脚本执行?您可以在退出事件处理程序中同时执行这两项操作(例如,只需调用 sys.exit()
  • @JerieWang 我想输入“%exit”,然后输入;我正在调试,我想在第一次退出时退出调试器,例如
  • these suggestions 之一可以工作吗?只是想在这里回答问题背后的问题。 :) 即一个建议是关闭退出确认:IPYTHON.rc.confirm_exit = False

标签: python ipython key-bindings


【解决方案1】:

这应该可以解决问题:

import pyautogui
from prompt_toolkit.key_binding import KeyBindings
from IPython import get_ipython
ip = get_ipython()

def exit_ipy(event):
    buffer = event.current_buffer
    buffer.insert_text('%exit') 
    pyautogui.press('enter') # simulates an enter press
   
ip = get_ipython()
registry = ip.pt_app.key_bindings
registry.add_binding(u'escape')(exit_ipy)

pyautogui 让你模拟一个按键,就像你自己做的一样,所以我认为这个解决方案会起作用 PS:我不能测试所以我没有

【讨论】:

  • 感谢使用pyautogui 的建议。有趣的是,形成了一个新行——相当于输入%exit\n,而不是提交击键。
  • 这肯定很奇怪,但正如我所说,我无法测试这个,因为我没有设置 IPython
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 2012-06-30
  • 2016-09-12
  • 2021-02-09
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多