Making iPython Virtualenv Aware

iPython is a great replace­ment for the stan­dard Python shell, but, out of the box, it doesn’t play well with virtualenv.

This can be fixed with a cou­ple of changes:

In the ter­mi­nal gen­er­ate an iPython default con­fig file:

ipython profile create

Open the newly gen­er­ated file:

vi ~/.ipython/profile_default/ipython_config.py

Add the fol­low­ing code at the end of the ipython_config.py file:

import site
from os import environ
from os.path import join
from sys import version_info

if 'VIRTUAL_ENV' in environ:
    virtual_env = join(environ.get('VIRTUAL_ENV'),
                       'lib',
                       'python%d.%d' % version_info[:2],
                       'site-packages')
    site.addsitedir(virtual_env)
    print 'VIRTUAL_ENV ->', virtual_env
    del virtual_env
del site, environ, join, version_info

And that’s it, iPython should now be vir­tualenv aware.

4 September, 2012 — one comment

One Comment


Paul McCann 30 November, 2012 03:53

Thanks! That came in handy. On my instal­la­tion, the ipython con­fig direc­tory is in ~/.config/ipython.



Leave a comment