BMW CarIT Logo Typo

Blog

News, ideas and events

Blog

A short note on virtualenv

Background

Although I have been programming in python for several years, I have only recently learned about virtualenv [1] .

Virtualenv is not a python library you use in your project, but on top of your project. It isolates your python environment and (additional) installed packages. This allows you to separate project specific packages from system-wide installed packages or from those installed in other virtual environments. So with virtualenv , you have the flexibility to install multiple different versions of the same package for different projects, without causing any conflicts. This is possible by the use of virtual environments, hence the name of this package.
This blogpost is intended to be a simple HowTo for myself and all other who are interested. If you want to learn more and/or get detailed information please refer to the official documentation or read this detailed article explaining virtualenv [2].

Installation/How to get virtualenv

The preferred way to acquire virtualenv is the installation via pip.

Installing virtualenv
$ [sudo] pip install virtualenv

In an ideal world this should be “the only” package you install into your base python system.

Creating a virtual environment

This step is required only once per project.

Create project virtual environment
$ mkdir project_folder
$ cd project_folder
$ virtualenv <venv_folder_name> 

It creates a subfolder structure to manage the libraries additionally installed with your project under .
It is also possible to place outside your project folder structure. This makes is easier to use the same virtual environment for more than one project (e.g. associated libraries).

If you need a special python interpreter in your project just specify it.

$ virtualenv -p /usr/bin/python2.7 <venv_folder_name>

Please refer to the official documentation to learn more about the various options of virtualenv .

Activation/Start using your virtual environment

In order to work with/use a virtual environment you have to activate it.

Activation
$ source <venv_folder_name>/bin/activate
<venv_folder_name> $ 

If activated virtualenv prepends the to your prompt. Now every package that is installed via pip goes into the virtual environment.

Deactivation

To stop working with a virtual environment you have to deactivate it.

Deactivation
$ deactivate

Conclusion

This conclusion is an easy one: Just use it!
With virtualenvwrapper [3] there is also tooling around which simplifies the usage of virtualenv even more.

Links

[1] Virtualenv documentation
[2] Virtualenv on the python-guide.org
[3] virtualenvwrapper