Working with multiple Python versions

We can use the pyenv tool for installing, managing, and using different Python installations. Pyenv – utility that uses shims for setting Python executable path.
Installation and configuration are pretty simple:

#Lets install all the additional stuff
sudo yum install zlib-devel zlibrary-devel zlibrary openssl openssl-devel
#This directory will contain all python versions and pyenv executable
sudo mkdir /opt/python
#You can use separate user for installing python modules, different
#versions, etc.
chown pyenv_admin:pyenv_admin /opt/python
#Lets log in this user and continue as it
su - pyenv_admin
cd /opt/python
git clone https://github.com/yyuu/pyenv.git

Now you need to modify the default PATH system variable for those OS users who will use pyenv and its Python installations. Just add the following code to the end of ~./bash_profile files in users’ home directories:

export PYENV_ROOT="/opt/python"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"

After that, you need to relogin. Now you can install additional Python installation of different versions (you need to have rw permissions on your pyenv installation directory – /opt/python in my example):

pyenv install 2.7.11

So from this moment, you can easily switch between Python versions (by priority):

  1. setting PYENV_VERSION variable
  2. setting version in .python-version file in the current directory
  3. setting version in version file in pyenv installation directory

Example:

[pyenv_admin@glados ~]$ python --version
Python 2.6.6
[pyenv_admin@glados ~]$ pyenv versions
* system (set by /opt/python/version)
2.7.12rc1
3.5.1
[pyenv_admin@glados ~]$ export PYENV_VERSION=2.7.12rc1
[pyenv_admin@glados ~]$ python --version
Python 2.7.12rc1
[pyenv_admin@glados ~]$

Simple, isn’t it? It’s also easy to install/uninstall modules to different Python installations – pip also works through shims.

Leave a comment