Working with multiple Python versions

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

#Lets install all the additional staff
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 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’s 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 version (you need to have rw persmissions 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 current directory
  3. setting version in version file in pyenv installation direcotory

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s