Python Virtual Environments

Sometimes, one Python environment may not be enough. For instance, you may find yourself working on multiple Django projects at once – each with different Python package requirements. I personally ran into this problem when writing a feature which required the bleeding-edge version of Django. Repeatedly installing/uninstalling different Django versions is redundant, and virtual environments are the answer.

To get started, install virtualenv and virtualenvwrapper:
pip install virtualenv
pip install virtualenvwrapper

Add the following to ~/.bashrc:
# virtualenvwrapper
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/

Lastly, create the virtual environment directory and execute ~/.bashrc:
mkdir ~/.virtualenvs
source ~/.bashrc

Now you can create isolated Python environments using mkvirtualenv envname. I have one called “rb”, and one called “rbalpha” which contain different Python packages. After an environment is activated, you’ll see (envname) next to your username in bash. You can activate an environment by simply using workon envname.

Once you are in your environment, Python packages can be installed in a similar manner as before. The only difference is you don’t use sudo when installing packages with pip or install. If you do this, the packages will be installed to the system’s Python environment.

Pro tip: To list the current environment’s Python packages, use pip freeze.


3 thoughts on “Python Virtual Environments

  1. Pingback: Dave: Winter Code Sprint 2012 « Review Board Student Blog

  2. Pingback: Charming Python and the mysterious case of libmysqlclient.18.dylib « Sparkica's Brainmachine

  3. Pingback: Review Board and the Django Debug Toolbar | Review Board Student Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s