python - 覆盖 ipython 退出函数 - 或者在其中添加 Hook

标签 python shell ipython

在我的项目中 manage ,我将 iPython 嵌入到:

from IPython import start_ipython
from traitlets.config import Config
c = Config()
c.TerminalInteractiveShell.banner2 = "Welcome to my shell"
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
start_ipython(argv=[], user_ns={}, config=c)

它运行良好并打开我的 iPython 控制台,但要离开 ipython,我只需键入 exitexit() 或按 ctrl+D.

我想做的是添加一个 exit hook 或用其他东西替换那个 exit 命令。

假设我有一个函数。

def teardown_my_shell():
    # things I want to happen when iPython exits

我如何注册要在我退出时执行的函数,甚至如何让退出执行该函数?

注意:我试图通过 user_ns={'exit': teardown_my_shell} 但没有成功。

谢谢。

最佳答案

首先感谢@user2357112,我学会了如何创建扩展和注册钩子(Hook),但我发现 shutdown_hook 已被弃用。

正确的方法就是简单。

import atexit

def teardown_my_shell():
    # things I want to happen when iPython exits

atexit.register(teardown_my_shell)

关于python - 覆盖 ipython 退出函数 - 或者在其中添加 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39499748/

相关文章:

linux - 根据输出从配置文件中解析变量

IPython:从特定行开始运行脚本

python - 为什么 Python 的枚举这么慢?

python - Google App Engine-如何添加lib文件夹?

python - Amazon lambda 不显示 python 日志

python - XML PARSER - 解析大文件以获得特定格式的输出

bash - Shell:连接到网站并访问字段

shell - KornShell 中的变量赋值

python - 进入交互式 session 以检查失败的单元测试

python - 如何在 Spyder/IPython/matplotlib 中再次获得交互式绘图?