在我的项目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,我可以只输入exit
或exit()
,或者按ctrl+D
。
我想要做的是添加一个exit hook
或用其他命令替换exit
命令。
假设我有一个函数。
def teardown_my_shell():
# things I want to happen when iPython exits
如何注册要在exit
时执行函数,甚至如何让exit
执行该函数?
注意:我试图通过user_ns={'exit': teardown_my_shell}
,但不起作用。
谢谢。
发布于 2016-09-15 11:58:37
首先感谢@user2357112,我学会了如何创建扩展和注册钩子,但我发现shutdown_hook
已被弃用。
正确的方法很简单。
import atexit
def teardown_my_shell():
# things I want to happen when iPython exits
atexit.register(teardown_my_shell)
发布于 2016-09-15 05:29:02
在谷歌上搜索IPython exit hook就会找到IPython.core.hooks
。从该文档中可以看出,您可以在IPython extension中定义一个退出挂钩,并使用IPython实例的set_hook
方法注册它:
# whateveryoucallyourextension.py
import IPython.core.error
def shutdown_hook(ipython):
do_whatever()
raise IPython.core.error.TryNext
def load_ipython_extension(ipython)
ipython.set_hook('shutdown_hook', shutdown_hook)
您必须将扩展添加到您的c.InteractiveShellApp.extensions
中。
https://stackoverflow.com/questions/39499748
复制相似问题