Issue
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.
Solution
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')
Answered By - magu_
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.