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>First thanks to @user2357112, I learned how to create an extension and register a hook, but I figured out that <code>shutdown_hook</code>is deprecated.</p>

<p>The right way is simply.</p>

<pre><code>import atexit

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

atexit.register(teardown_my_shell)
</code></pre>

python shell ipython