Monday, February 8, 2016

How to make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you install things use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

By using -I, you will always reinstall packages, even if they already exist in the systemwide site-packages directory. If you use -U instead, it will install newer versions of packages into your virtualenv, but won't reinstall any packages that are already available in the system with the required version. – Danilo BargenFeb 4 '14 at 17:09 


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']

No comments:

Post a Comment