Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atexit alternative for ipython

python has atexit module to register functions to run prior to closing of the interpreter. This question nicely why atexit is not called.

I'm wondering if there is an alternative for ipython to register a function prior to exiting something which has been run with %run <name>? Ideally I would like to create a decorator which works registers in either module depending on the interpreter.

like image 675
magu_ Avatar asked Aug 31 '25 22:08

magu_


1 Answers

Thanks Thomas K for the good comment. In case he writes an answer I'll accept his. Otherwise this piece of code might benefit somebody else:

# 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')
like image 147
magu_ Avatar answered Sep 03 '25 20:09

magu_