virtualenv and pip – A python environment in 60 seconds

I’m a PHP developer completely new to Python. For this project, I want to make sure that everyone’s using the same environment, which means virtualenv and pip. As an added bonus, this means that your pip installs are per project, and not system wide. Here’s a quick guide to getting it all set up on Ubuntu.

First, install pip

sudo apt-get install python-pip

Then install virtualenv

sudo pip install virtualenv

Next, create your project directory and cd into it

mkdir new-project && cd new-project

You’ll want to create a virtualenv environment for this new project (using the python2.7 interpreter)

virtualenv -p /usr/bin/python2.7 --no-site-packages .virtualenv

The next thing to do is to enable it

source .virtualenv/bin/activate

And install any dependencies

pip install twisted

Once you’ve installed your dependencies, you’ll want to record them somewhere. By convention, pip uses requirements.txt. To generate this file from your currently installed modules, use the following command:

pip freeze > requirements.txt

To install the dependencies from the file, use the following command:

pip install -r requirements.txt

Finally, you’ll want to share this project via git or a similar tool. Make sure that your .virtualenv folder is in your ignore file. Your coworkers will be able to rebuild the environment easily.

echo ".virtualenv" > .gitignore
git add .
git commit -m "Initial commit"

When a coworker downloads the project, all they need to do to get up and running is run the following:

virtualenv -p /usr/bin/python2.7 .virtualenv && source pyenv/bin/activate && pip install -r requirements.txt

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply