5

In my project manage, I am embedding iPython with:

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)

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

What I want to do is to add an exit hook or replace that exit command with something else.

Lets say I have a function.

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

How do I register that function to be executed when I exit or even how to make exit to execute that function?

NOTE: I tried to pass user_ns={'exit': teardown_my_shell} and doesn't work.

Thanks.

2 Answers2

6

First thanks to @user2357112, I learned how to create an extension and register a hook, but I figured out that shutdown_hookis deprecated.

The right way is simply.

import atexit

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

atexit.register(teardown_my_shell)
2

Googling IPython exit hook turns up IPython.core.hooks. From that documentation, it looks like you can define an exit hook in an IPython extension and register it with the IPython instance's set_hook method:

# 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)

You'll have to add the extension to your c.InteractiveShellApp.extensions.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • The method of registering an extension works, but I found that shutdown_hook is deprecated, I am goin to put the solution as anwer – Bruno Rocha - rochacbruno Sep 15 '16 at 03:56
  • @rochacbruno: Huh. That wasn't in the documentation I found, but Google suggests you're right. I figured shutdown_hook was for when you want to do something when the IPython instance is shutting down, but the Python interpreter itself might still remain active. – user2357112 Sep 15 '16 at 04:56
  • this seems to be deprecated: `UserWarning: Hook shutdown_hook is deprecated. Use the atexit module instead.` – reox Feb 12 '19 at 08:11