在我的项目中 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
我如何注册要在我退出
时执行的函数,甚至如何让退出
执行该函数?
注意:我试图通过 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/