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.
-
From the command prompty, install the libraries needed for Python.
sudo yum install zlib-devel openssl openssl-devel
-
Install wget.
sudo yum install wget
-
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
-
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"
-
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.
-
In the ~/.bash_profile, remove the alias for python that we just added.
-
Source the profile.
source ~/.bash_profile
-
Install virtualenv.
sudo yum install python-pip
sudo pip install virtualenv
-
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