覆盖 ipython 退出函数 - 或在其中添加钩子

Bru*_*uno 4 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)
Run Code Online (Sandbox Code Playgroud)

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

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

假设我有一个功能。

def teardown_my_shell():
    # things I want to happen when iPython exits
Run Code Online (Sandbox Code Playgroud)

当我exit或什至如何exit执行该函数时,如何注册要执行的函数?

注意:我试图通过user_ns={'exit': teardown_my_shell}但不起作用。

谢谢。

Bru*_*uno 5

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

正确的方法很简单。

import atexit

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

atexit.register(teardown_my_shell)
Run Code Online (Sandbox Code Playgroud)