Type Slowly

Nov 3

Setting up a Python development environment on Ubuntu

I’ve got to do a few assignments in Python for university, and wanted to set up my laptop (running Ubuntu Maveric) to do this. When I’m doing any Ruby development I use the excellent RVM to create a personal (or even project-specific) development environment for my work, and wanted to do the same with Python, not least so that my tentative first experiments in it were sandboxed in some way (I have bad memories of messing up my Cabal install when hacking on some Haskell, causing XMonad to fail to launch next time I rebooted.

Happily, the virtualenv package provides a useful python equivalent to RVM. Simply:

sudo apt-get install python-pip python-virtualenv

As it sounds, python-virtualenv is the apt package that installs virtualenv - python-pip is a python equivalent of soemthing like RubyGems which might come in useful later when I need to install libraries. Now set up a new virtual python environment:

virtualenv --no-site-packages ~/.python-local

This creates a fresh python install in the folder ~/.python-local - the no-site-packages option makes sure your local environment doesn’t import packages from elsewhere on the system- it’s totally stand-alone.

Then, just make sure that the bin directory in your local python directory is on your path, before the system bin directories (so your local one takes precedence) - I use zsh, so that involved adding ~/.python_local/bin to this line in .zshrc, like so:

export PATH=/home/tim/.cabal/bin:/home/tim/bin:/home/tim/.python_local/bin:$PATH

Then close your terminal window, open a new one to allow the PATH changes to take effect, and marvel at your new sandboxed python install! (try ‘which python’, ‘which pip’ or ‘which easy_install’ if you don’t believe me!).

There’s one gotcha however - you’ll notice that if you run virtualenv again (if you can’t get enough stand-alone python installations and just have to have MORE!), you’ll get an error:

Traceback (most recent call last):   File "/usr/bin/virtualenv", line 2, in      import virtualenv ImportError: No module named virtualenv 

It’s pretty easily explained - the virtualenv command you called (in /usr/bin) called out to the python interpreter (now in ~/.python_local/bin, which obviously couldn’t find the virtualenv libraries that are installed in the system python installation. Simply install virtualenv into your new development sandbox and all is fine again:

easy_install virtualenv

blog comments powered by Disqus
Page 1 of 1