Virtualenv is a tool that lets you create isolated environments for your Python projects. It addresses the issues of application dependencies and versions of software for each of your Python projects. Imagine that you had one project that required v1 of the Foo library and then another project that required v2 of the same library.
So how can we use both these applications? If you install everything globally it’s easy to end up in a situation where you’ve unintentionally upgraded an application that shouldn’t be upgraded. Or you have to create multiple development machines.
This is where Virtualenv comes into play by creating an isolated environment with its own installation directories, that doesn’t share libraries with other virtual environments.
To install Virtualenv we use PIP (Python Install Package) tool. This is the same on mac and windows.
$ pip install virtualenv
Running the command below will create a folder name “venv” on your system that, once “activated”, will be used to store and isolate any application requirements.
$ virtualenv venv
To specify a certain version of python
$ virtualenv –python=/usr/bin/python2.6 venv
Now we need to activate the virtualenv.
on a mac
$ source venv/bin/activate
Once activated the virtual environment will be indicate by displaying the Virtualenv name in the terminal prompt.
You can now start to install packages for your project that will be isolated from all other environments.
(venv) $ pip install Flask
(venv) $ pip install awscli
(venv) $ pip uninstall Flask
(venv) $ pip uninstall awscli
When in your virtual environment you can used the pip freeze command to view a list of packages that have been installed.
(venve) $ pip freeze
To leave the virtual environment run the following command.
(venv) $ deactivate
This was a quick guide to setup a python project environment using virtualenv. As always check out the official documentation or help for “pip” and “virtualenv” commands.