Motivation
virtualenv is a great tool to isolate Python interpreters and packages.
Comes in handy when:
- you don't want to, or can't install Python packages system-wide (to
/usr/local/lib/python2.7/site-packages
on Debian, for example). - only those packages actually required by an application should be made available to it.
- an application needs a version of a package that is older than the one that already is, or would be installed (by your operating system's package manager, for example).
- packages for a specific application should be kept at a certain version (because you want to check the changelogs first, and upgrade applications one by one), or at least they shouldn't be updated automatically, while it still should be possible to update those packages for other applications.
- you want to test a single code base manually with multiple Python
interpreters (you can, for example, create environments
env2.7
andenv3.3
, and activate one of them as necessary).
Basic Usage
Usually, if virtualenv is installed, a virtual environment in
./some-app-env
is created like so:
$ virtualenv some-app-env
As virtualenv installs pip automatically, you can install packages right away after activating the virtual environment:
$ . some-app-env/bin/activate
(some-app-env)$ pip install Flask SQLAlchemy WTForms
Python 3.3
Starting with version 3.3, the Python standard library includes the venv module that you can use instead of installing virtualenv.
There are some differences in using it, compared to the third-party module and earlier Python versions, though.
Creation
Instead of virtualenv
, use the pyvenv
(or pyvenv-3.3
) command to
create a virtual environment:
$ pyvenv some-app-env
A note from personal experience: It's pyvenv
(as in "py-vee-env"), not
pyenv
(like rbenv
). I even made this mistake again when writing this
article …
You might want to make sure it actually provides version 3.3 of Python:
$ . some-app-env/bin/activate
(some-app-env)$ python -V
Python 3.3.2+
Availability of setuptools and pip
As opposed to virtualenv, venv does not pre-install pip (and setuptools, for that matter), so you have to do it yourself.
First, install setuptools (note: there are alternative ways to do that) as it is required by pip:
(some-app-env)$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python
Then, install pip (can be installed differently as well):
(some-app-env)$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
(some-app-env)$ python get-pip.py
… and you're ready to go!
Note: You might read about the distribute package here and there. It is a fork of setuptools, and it has been merged back into it as of version 0.7.