覆盖ipython退出函数 - 或添加钩子 [英] Override ipython exit function - or add hooks in to it
问题描述
在我的项目管理中,我使用以下内容嵌入iPython:
In my project manage, I am embedding iPython with:
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我可以键入退出
或退出()
或按 ctrl + D
。
It works well and opens my iPython console, but to leave ipython I can just type exit
or exit()
or press ctrl+D
.
我想要做的是添加退出挂钩
或替换退出
带有别的东西的命令。
What I want to do is to add an exit hook
or replace that exit
command with something else.
假设我有一个功能。
def teardown_my_shell():
# things I want to happen when iPython exits
我如何注册当我退出
或甚至如何让退出
执行该功能时要执行的功能?
How do I register that function to be executed when I exit
or even how to make exit
to execute that function?
注意:我试图传递 user_ns = {'exit':teardown_my_shell}
并且不起作用。
NOTE: I tried to pass user_ns={'exit': teardown_my_shell}
and doesn't work.
谢谢。
推荐答案
首先感谢@ user2357112,我学习了如何创建扩展和注册一个钩子,但我发现 shutdown_hook
已被弃用。
First thanks to @user2357112, I learned how to create an extension and register a hook, but I figured out that shutdown_hook
is deprecated.
正确的方法很简单。
import atexit
def teardown_my_shell():
# things I want to happen when iPython exits
atexit.register(teardown_my_shell)
这篇关于覆盖ipython退出函数 - 或添加钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!