Wednesday, 8 May 2013

A Short note about Virtual Environments.


Virtual Environments


A Virtual Environment, is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects.
By using this, you can work on a project which requires Django 1.3 while also maintaining a project which requires Django 1.0.
virtualenv is a tool to create isolated Python environments.

Install it via pip:
     $ pip install virtualenv

Basic functions of virtualenv:
  1. Create a virtual environment
      $ virtualenv project
     This creates a copy of Python in whichever directory you ran the command in, placing it in a folder
     named project.
   
     2. Activating a virtual environment
    $ source project/bin/activate
     We can then begin installing any new modules without affecting the system default Python or other
     virtual environments.

    3. Deactivating a virtual environment
     
          $ deactivate

     This puts us back to the system’s default Python interpreter with all its installed libraries.

    4. Deleting a virtual environment
    To delete a virtual environment, just delete its folder.


virtualenvwrapper


virtualenvwrapper is a set of extensions to virtualenv tool. The extensions include wrappers for creating and deleting virtual environments and otherwise managing our development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies.

Features:
  1. Organizes all of your virtual environments in one place.
  2. Wrappers for managing your virtual environments (create, delete, copy).
  3. Use a single command to switch between environments.
  4. User-configurable hooks for all operations.
  5. Tab completion for commands that take a virtual environment as argument.
  6. Plugin system for more creating sharable extensions
Install it via pip:

$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualwrapper.sh
$ mkvirtualenv env1

Now we can install some software into the environment:
(env1)$ pip install django

We can see the new package with lssitepackages:

(env1)$ lssitepackages
 Django-1.1.1-py2.6.egg-info     easy-install.pth
 distribute-0.6.10-py2.6.egg     pip-0.6.3-py2.6.egg
 django                          setuptools.pth
We can create multiple environments:
(env1)$ mkvirtualenv env2

and so on...

We can switch between environments with workon:

(env2)$ workon env1
(env1)$