Setting up Python on Linux and using Virtualenv

I am writing this because I found out that there are a couple of different ways to install Python on a *nix based computer. I ran around in circles for a while before I figured it out.

Basically, I realized this. In order to have multiple versions of Python

A) Install the Python version and then alias to it.

B) Use something like virtualenv to allow me to switch between versions.

After reading this post, virtualenv seemed like a powerful option. It seems to follow the similar pattern of nvm and sdkman, which are really great tools for developers that want to rapidly switch between different projects.

So, here is how I install Python now.

This is on a CentOS 6.5 machine which has Python 2.6 installed on it.

  1. From the command prompty, install the libraries needed for Python.

    sudo yum install zlib-devel openssl openssl-devel

  2. Install wget.

    sudo yum install wget

  3. Install Python 2.7. I use the –prefix command to install it to an isolated location.

    cd ~

    wget http://www.python.org/ftp/python/2.7.8/Python-2.7.8.tar.xz

    xz -d Python-2.7.8.tar.xz

    tar -xvf Python-2.7.8.tar

    cd ~/Python-2.7.8

    ./configure –prefix=/opt/python2.7

    make

    sudo make altinstall

  4. Now, create an alias in your ~/.bash_profile to the new version of Python. Add the following line to the bottom of the file.

      alias python="/opt/python2.7/bin/python2.7"
    

  5. Source the profile.

    source ~/.bash_profile

Now, when you type python at the command prompt, it should bring you into the 2.7 shell and not the 2.6. The downside here is all of your python packages will be shared. You risk running the wrong package when you update Python.

Virtualenv

Using virtualenv, you could skip the step of having to mess with the aliases. Another benefit is the pip packages stay isolated from the other versions.

So, from the last step, here’s how we can install virtualenv.

  1. In the ~/.bash_profile, remove the alias for python that we just added.

  2. Source the profile.

    source ~/.bash_profile

  3. Install virtualenv.

    sudo yum install python-pip

    sudo pip install virtualenv

  4. Create the virtual environment.

    virtualenv –system-site-packages -p /opt/python2.7/bin/python2.7 ~/python-vms/python2.7

    cd ~/python-vms/python2.7

    source bin/activate

Leave a Reply