}

How to switch between multiple python interpreters

Created:

Introduction

Having multiple versions of python is very helpful when you need to make sure that your code is compatible against Python 2 and 3.

In this tutorial we are going to show how to install and use pyenv.

Pyenv is a project that was forked from rbenv and was modified for Python. This project allow to easily change and install different Python interpreters, like the most used cpython, pypy or even stackless.

We also going to show how to combine pyenv and virtualenvs, this will allow you to have each python implementation with independent virtualenvs for each one.

Step 1: Installing pyenv

Installation of pyenv is very easy, we need to do a curl to the pyenv-install github repository:

curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

To enable pyenv add this lines to .bashrc or .zshrc:

export PATH="~/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Now do a source ~/.bashrc to enable pyenv.

Step 2: Installing a python interpreter

If everything went fine in step 1, you are ready to use pyenv. Next step will teach you how to install python 3.5.1. Let's install it with this command:

pyenv install 3.5.1

You should see something like this:

Downloading Python-3.5.1.tgz...
-> https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Installing Python-3.5.1...
Installed Python-3.5.1 to.....

If you want to list all available python version to install, just do a pyenv install -l.

Step 3: Install virtualenv plugins

We are going to install virtualenv plugin for pyenv.

git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv

Add the following to your .bashrc configuration file and restart your bash:

eval "$(pyenv virtualenv-init -)"
exec "$SHELL"

Use Python 3.5.1 with virtualenv example

pyenv virtualenv 3.5.1 test_virtualenv_3.5.1

And now enter to the virtualenv with:

pyenv activate test_virtualenv_3.5.1

Instead of activate you can use deactivate to disable the virtualenv.

Conclusion

Pyenv is a great tool to work with multiple python versions and with pyenv virtualenv plugin we manage to have isolated environments for each python version, which makes this tool very versatile.