Directory-Specific Ipython Settings & History

Directory-Specific Ipython Settings & History

Suppose that you have multiple projects for which you use ipython to run code, analyze data, etc. Wouldn't it be nice that whenever you were working on that project, all of your ipython settings and command history were there from the last time you were working on it?

Step 1: direnv

Direnv is a tool which allows you to specify directory-specific environment settings by creating a file called .envrc in a directory. Then, any time you enter that directory, direnv detects that there is a .envrc file, and sets environment variables accordingly. If you then leave that directory, those variables are unset automatically.

  1. Install direnv (generally package-manager install direnv should work, but system-specific instructions can be found here). On mac brew install direnv will work if you have Homebrew installed.
  2. Hook direnv into your shell by following the instructions here. With zsh, just add eval "$(direnv hook zsh)" to your ~/.zshrc file.
  3. Create a file called .envrc in your project folder
  4. Add one line do that file: export IPYTHONDIR=.ipython
  5. When you have saved that file (and any time that file changes in the future) you should be prompted to allow it to run, by typing direnv allow.

For more things you can do with direnv (e.g. automatically activating your virtual environment), see their Wiki.

Step 2: Create ipython profile

Create an ipython profile in the .ipython directory of your project folder. ipython profile create default --ipython-dir=.ipython

Technically, you're now done! Your command history within ipython is now saved to your project folder, so any time you go into ipython from inside that folder, you will have access to your project-specific command history.

Step 3: Customize ipython profile (optional)

You can now edit .ipython/profile_default/ipython_config.py and specify project-specific settings by adding lines to that file. Here is an example config file from ipython. My favorite things to set are autoreload, and basic imports that you need on a regular basis. Here is how you can get both of those, by adding the following to the bottom of the ipython_config.py file.

c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.InteractiveShellApp.exec_lines.append('print("Warning: disable autoreload in ipython_config.py to improve performance.")')
c.InteractiveShellApp.exec_lines.append('import numpy as np')
c.InteractiveShellApp.exec_lines.append('import scipy')