Using Virtual Environments in Python 2.7

In this post I’ll cover setting up a virtual environment in Python 2.7 in preparation for working out a RESTful app in Flask.

Installation

So, I’ll assume you’re running a Debian flavor of Linux. You’ll need curl, so if you don’t already have that, run the following from the command line:

sudo apt-get install curl

Then, using curl, you can install pip.

curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python2.7

Then, using pip, you can install virtualenv.

sudo pip install virtualenv

Now, we’re good to go.

Creating a Virtual Environment

First create a directory to hold your virtual environments.

mkdir venvs

Next, create a virtual environment by specifying the root directory of that environment. By default, no site-packages are installed.

virtualenv venvs/one

This creates a virtual environment in ./venvs/one/. To activate this environment, use the command,

source venvs/one/bin/activate

This will change your command line to reflect that you are working in a virtual environment. To get out of the virtual environment, execute the following:

deactivate

Seeing What is Installed

To see what is installed in your virtual envrionment, use the yolk utility. First install using apt-get

sudo apt-get install yolk

And then use the following from inside the virtual environment to see what you have installed.

yolk -l

One thought on “Using Virtual Environments in Python 2.7”

  1. are you using this for testing dependencies etc. when developing new installable python packages?
    or what is the primary use of a python virtual environment? (less damage when py-script crashes inside this kind of ‘sandbox’?)

Comments are closed.