Getting started with virtualenv on Ubuntu 12.04
virtualenv is one of those tools that every Python developer should use. It lets you create isolated Python environments for your projects so you can try out different versions of packages/libraries the applications use on the same machine.
You could do something similar using virtualization software such as VMware or VirtualBox, but they take up more resources and take longer to set up. With virtualenv, you can set up these isolated environments in seconds!
I’m actually guilty of not taking advantage of this tool at my previous job. It was a Windows environment and I remember trying out virtualenv but I gave up due to different issues I ran into (usually paths/environment variables issues, though the newer versions of virtualenv might work better with Windows now). With Linux, getting it set up is very simple. Everything worked as expected and I can’t imagine working on a Python project now without it.
Installation
1. You should already have Python 2.x installed, but in case you don’t, you can install it with:
sudo apt-get install python2.7
2. Install pip.
sudo easy_install pip
3. Install virtualenv using pip.
sudo pip install virtualenv
Creating and Activating a virtualenv Environment
1. Select a location where to store all the files created by virtualenv. In my case, I like to place them inside my project directory in a hidden folder called .venv (I use git and I just add an entry to my .gitignore file to skip the .venv directory when committing code).
virtualenv .venv
This command will use the –no-site-packages option by default, which will prevent access to the global site-packages directory when the virtual environment is active.
2. Activate the environment.
source .venv/bin/activate
3. You should see your bash shell change to include (.venv) (or whichever name you chose for your environment) in front of the prompt.
If you want the prompt prefix to be different from the default (env_name), you can use the –prompt option. For example:
virtualenv .venv --prompt=”<mycoolproj>”
While in this mode, your applications will use only the packages in your virtual environment when you run them. You can use the pip freeze command to see which packages are currently installed.
4. Install packages with pip.
pip install Django==1.4.5
If you have arequirementsfile you can do:
pip install -r requirements.txt
Deactivating a virtualenv Environment
1. Simply type:
deactivate
Deleting the virtualenv Environment
1. Simply delete the entire directory created by virtualenv.
rm –rf .venv
Tags: linux, python, tech, software development