virtualenv: Specifing which packages to use system-wide vs local

Question:

Possible Duplicate:
Make virtualenv inherit specific packages from your global site-packages

Is there a way to create a virtualenv for Python and specify which packages should be used (inherited) from the system-wide installation, and which ones it should ignored from the system-wide installation?

More specifically, say for example that there is a system-wide installation of:

numpy
scipy
matplotlib

I would like to create a virtual environment such that:

  • Uses the system-wide installation of numpy and scipy
  • Ignores the system-wide matplotlib, and lets me install/upgrade my own versions of it (with pip -U matplotlib).

Is this possible?

Answers:

The simplest way to do this is to create a virtualenv which includes the system site packages and then install the versions that you need:

$ virtualenv --system-site-packages foo
$ source foo/bin/activate
$ pip install Django==1.4.3

You can also clean up the virtualenv afterwards by checking the output of pip freeze and removing the packages that you do not want. (removing system-site-packages with pip uninstall does no longer work for newer versions of virtualenv)

Another way would be to create a clean virtualenv and link the parts that you need:

$ virtualenv --no-site-packages foo
$ source foo/bin/activate
$ ln -s /usr/lib/python2.7/dist-packages/PIL* $VIRTUAL_ENV/lib/python*/site-packages

The commands might be slightly different on a non-unixish environment. The paths also depend on the system you are using. In order to find out the path to the library start up the python shell (without an activated virtualenv), import the module and check module_name.__path__. e.g.

Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__path__
['/usr/lib/python2.7/dist-packages/PIL']

Also if you have created your virtualenv with --system-site-packages, it is possible to install newer version than what is in the system with pip install --upgrade --ignore-installed numpy.

Answered By: bikeshedder
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.