26th June 2015 by aegeuana_sjp_admin

Python Virtual Environment Tutorial

This is a basic tutorial designed to help you setup a virtualenv and start using it.
The purpose of virtualenv is to isolate Python environments and make sure there are no conflicts when you have multiple applications deployed on the same machine. In short if you have two or more Python applications which require different versions of the same package can be nicely isolated by using virtualenv.
The installation process is straightforward:
[code language=”python”]
pip install virtualenv
After the installation you will have a virtualenv command available, you can now start creating your first virtual environment.
[code language=”python”]
virtualenv venv_foo
This will create a folder venv_foo which will be your isolated environment. You can create as many environements as you wish. Now let’s activate the environment and start installing some packages within that environment.
[code language=”python”]
. venv_foo/bin/activate
pip install python-dateutil
Once you have activated the virtual environment your command line will indicate which virtual environment you are in. Everything you install within that environment will only be available when you are within that environment. You can list the installed packages within that environment by using the pip freeze.
[code language=”python”]
pip freeze
It is also possible to run stand alone python scripts which make use of a specific virtual environment.
[code language=”python”]
import os
import sys
# setup virtual env
if == ‘posix’:
bin_name = ‘bin’
# be nice to win32
bin_name = ‘Scripts’
activate_this = ‘/path/to/your/venv/%s/’ % bin_name
execfile(activate_this, dict(__file__=activate_this))
Once you are done and you want to quit the environment you can use the following command:
[code language=”python”]
Deleteing a virtual environment is as simple as deleting the folder.

Leave a Reply

Your email address will not be published. Required fields are marked *