Getting Started with VirtualEnv
July 20, 2011
I want to use VirtualEnv to manage my python environment, particularly because I'm using gunicorn as a wsgi server, and I want to be able to upgrade gunicorn for one particular application without affecting others.
VirtualEnv creates multiple distinct python environments - if you install libraries whilst inside a virtualenv, these will only be available when that env is activated.
Installation
We're going to install virtualenv, and then install some bash scripts designed to make working with virtualenv simpler.
# easy_install virtualenv # easy_install virtualenvwrapper
Add the following lines to .bashrc
in your home area:
export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh
This sets up a hidden directory in your home area which will contain the virtualenv configuration.
Next, reload the .bashrc
file using
$ source ~/.bashrc
Create VirtualEnv
To create a new virtualenv, run mkvirtualenv
followed by the name you want to use for the environment:
drumcoder@drumcoder ~$ mkvirtualenv patrons1 New python executable in patrons1/bin/python Installing setuptools............done. Installing pip...............done. virtualenvwrapper.user_scripts creating /home/drumcoder/.virtualenvs/patrons1/bin/predeactivate virtualenvwrapper.user_scripts creating /home/drumcoder/.virtualenvs/patrons1/bin/postdeactivate virtualenvwrapper.user_scripts creating /home/drumcoder/.virtualenvs/patrons1/bin/preactivate virtualenvwrapper.user_scripts creating /home/drumcoder/.virtualenvs/patrons1/bin/postactivate virtualenvwrapper.user_scripts creating /home/drumcoder/.virtualenvs/patrons1/bin/get_env_details
This will also switch to the new virtualenv and will show the name of it in your prompt
(patrons1)drumcoder@druncoder:~$
To move back out of a virtualenv, run deactivate
:
(patrons1)drumcoder@drumcoder:~$ deactivate drumcoder@drumcoder:~$
To list available virtualenvs, run workon
.
drumcoder@drumcoder:~$ workon patrons1
To select a virtualenv, use workon
followed by the env name.
drumcoder@drumcoder:~$ workon patrons1 (patrons1)drumcoder@drumcoder:~$
To install dependencies into the virtualenv from a requirements.txt file, use the following command:
(patrons1)drumcoder@drumcoder:~$ pip install -r requirements.txt