Search code examples
pythonipythonjupyter-notebook

iPython - set up magic commands in configuration file


I use iPython mostly via notebooks but also in the terminal. I just created my default profile by running ipython profile create.

I can't seem to figure out how to have the profile run several magic commands that I use every time. I tried to look this up online and in a book I'm reading but can't get it to work. For example, if I want %debug activated for every new notebook I tried adding these lines to my config file:

c.InteractiveShellApp.extensions = ['debug']

or

c.TerminalPythonApp.extensions = ['debug']

and I either get import errors or nothing. My (closely related) questions are the following:

  1. What line to do I add to my ipython config file to activate magic commands? Some require parameters, e.g. %reload_ext autoreload and %autoreload 2. How do I also pass these parameters in the config file?

  2. Can I separate which get added for terminal vs. notebooks in a single config file or must I set up separate profiles if I want different magic's activated? (e.g., matplotlib inline or not). Do the two lines above affect notebooks vs. terminal settings (i.e., c.InteractiveShellApp vs. c.TerminalPythonApp)?

Thank you!


Solution

  • Execute magics as follows:

    get_ipython().magic(u"%reload_ext autoreload")
    get_ipython().magic(u"%autoreload 2")
    

    You can put those lines in your startup script here:

    ~/.ipython/profile_default/startup/00-first.py
    

    Update: as of IPython v0.13, the run_line_magic function should be used instead of the magic function with:

    get_ipython().run_line_magic("reload_ext", "autoreload")
    get_ipython().run_line_magic("autoreload", "2")
    

    otherwise you get a deprecation warning.