Recently I started developing my python applications using virtualenv so that I don’t clutter up the system’s python installation with non-system python packages.

Everything was good until I wanted to use IPython instead of python’s shell…

The issue is that virtualenv creates a different python executable that includes the virtualenv‘s packages into sys.path while IPython stays unaware of the virtualenv‘s packages.

Yet, there’s a solution!!!

In order to solve this issue, IPython comes along to save the day.

IPython provides a way to include additional code to be executed when IPython‘s shell is started.

First, the small script that allows IPython to get virtualenv‘s packages into its sys.path.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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

Save the above snippet into your user’s IPython configuration directory ~/.ipython. Save it has, for example, virtualenv.py.

Now, as IPython’s documentation suggests, edit ~/.ipython/ipy_user_conf.py and somewhere inside the main() function add:

1
2
def main():
    execf('~/.ipython/virtualenv.py')

Now, the next time you start IPython‘s shell, if you’ve activated your virtualenv environment, you’ll also get the packages from there too.

1
2
3
4
Develop:user@machine:~$ ipython
VIRTUAL_ENV -> /home/user/.virtual_python/lib/python2.5/site-packages

In [1]:

And that’s it, there you have your virtualenv aware IPython shell!


Comments

comments powered by Disqus