Override ipython exit function - or add hooks in to it
<p>In my project <a href="http://github.com/rochacbruno/manage" rel="nofollow">manage</a>, I am embedding iPython with:</p>

<pre><code>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)
</code></pre>

<p>It works well and opens my iPython console, but to leave ipython I can just type <code>exit</code> or <code>exit()</code> or press <code>ctrl+D</code>.</p>

<p>What I want to do is to add an <code>exit hook</code> or replace that <code>exit</code> command with something else.</p>

<p>Lets say I have a function.</p>

<pre><code>def teardown_my_shell():
    # things I want to happen when iPython exits
</code></pre>

<p>How do I register that function to be executed when I <code>exit</code> or even how to make <code>exit</code> to execute that function?</p>

<p>NOTE: I tried to pass <code>user_ns={'exit': teardown_my_shell}</code> and doesn't work.</p>

<p>Thanks.</p>

<p>Googling <a href="https://www.google.com/search?q=ipython%20exit%20hook" rel="nofollow">IPython exit hook</a> turns up <a href="http://ipython.readthedocs.io/en/stable/api/generated/IPython.core.hooks.html?highlight=core.hooks#module-IPython.core.hooks" rel="nofollow"><code>IPython.core.hooks</code></a>. From that documentation, it looks like you can define an exit hook in an <a href="https://ipython.org/ipython-doc/2/config/extensions/index.html" rel="nofollow">IPython extension</a> and register it with the IPython instance's <code>set_hook</code> method:</p>

<pre><code># whateveryoucallyourextension.py

import IPython.core.error

def shutdown_hook(ipython):
    do_whatever()
    raise IPython.core.error.TryNext

def load_ipython_extension(ipython)
    ipython.set_hook('shutdown_hook', shutdown_hook)
</code></pre>

<p>You'll have to add the extension to your <code>c.InteractiveShellApp.extensions</code>.</p>

python shell ipython