pyenv lets us to easily switch between multiple versions of Python. It allows to change the global Python version on a per-user basis, provides support for per-project Python versions. Also, it allows overriding the Python version with an environment variable.

Installation

Clone pyenv repo in your desired location.

git clone https://github.com/pyenv/pyenv.git ~/.pyenv

Create environment variable PYENV_ROOT which points to the path of pyenv and add $PYENV_ROOT/bin to your $PATH.

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc

Add pyenv init at the end of the shell configuration file.

echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bashrc

Install build dependencies.

sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev

Restart the shell so the path changes take effect.

exec "$SHELL"

If everything works until now, then the following command will show the currently active Python version. In case, you are using the default version of Python that comes with Ubuntu, it will show system (set by ...).

pyenv version

Commands

Some of the common pyenv commands:

pyenv version

Displays the currently active Python version.

pyenv versions

Lists all Python versions known to pyenv, and shows an asterisk next to the currently active version.

pyenv install

Install a Python version.

pyenv install <version>

To list the all available versions of Python:

pyenv install --list

pyenv local

Sets a local application-specific Python version.

$ pyenv local 2.7.6

pyenv global

Sets the global version of Python to be used in all shells.

$ pyenv global 2.7.6

pyenv shell

Sets a shell-specific Python version.

pyenv shell 2.7.6

For more commands, visit pyenv commands For detailed documentation, visit pyenv