ipython 的 atexit 替代方案

atexit alternative for ipython

python atexit module to register functions to run prior to closing of the interpreter. This question 很好地解释了为什么不调用 atexit。

我想知道 ipython 是否有替代方法可以在退出 运行 和 %run <name> 之前注册一个函数?理想情况下,我想创建一个装饰器,它可以在任何一个寄存器中工作 模块取决于解释器。

感谢 Thomas K 的好评。如果他写了一个答案,我会接受他的。否则这段代码可能会使其他人受益:

# exit_register runs at the end of ipython %run or the end of the python interpreter
try:
    def exit_register(fun, *args, **kwargs):
        """ Decorator that registers at post_execute. After its execution it
        unregisters itself for subsequent runs. """
        def callback():
            fun()
            ip.events.unregister('post_execute', callback)
        ip.events.register('post_execute', callback)


    ip = get_ipython()
except NameError:
    from atexit import register as exit_register


@exit_register
def callback():
    print('I\'m done!')


print('Running')