Working with Virtualenv

By | March 3, 2018

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.

Intallation

To install Virtualenv we use PIP (Python Install Package) tool. This is the same on mac and windows.

$ pip install virtualenv

Usage

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

on windows

c:\> venv\Scripts\Activate.bat

Once activated the virtual environment will be indicate by displaying the Virtualenv name in the terminal prompt.

(venv) $

(venv) c:\>

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

awscli==1.14.16

beautifulsoup4==4.6.0

boto3==1.5.33

botocore==1.8.47

……………………………………………

To leave the virtual environment run the following command.

(venv) $ deactivate

(venv) c:\>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.

 

Leave a Reply

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