What is pyenv? Why pyenv?

Installation

on macOS, install using brew

# install pyenv
brew update
brew install pyenv
# setup env
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
# Zsh note: Modify your ~/.zshenv file instead of ~/.bash_profile.
# Ubuntu and Fedora note: Modify your ~/.bashrc file instead of ~/.bash_profile.

Install Multiple Python Version

# List all available versions
pyenv install -l

# Note this may take a while
# We'll install each latest minor release
pyenv install 2.6.9
pyenv install 2.7.12
pyenv install 3.1.5
pyenv install 3.2.6
pyenv install 3.3.6
pyenv install 3.4.5
pyenv install 3.5.2
#pyenv install 3.6-dev

# List current python (should still be `system`)
pyenv which python

# List all versions installed
pyenv versions

# Outputs:
* system (set by /Users/anillakhman/.pyenv/version)
2.6.9
2.7.12
3.1.5
3.2.6
3.3.6
3.4.5
3.5.2

How to Use It?

Switching versions globally

# List the current global python version
pyenv global
# `system`

# List all installed versions
pyenv versions
# * system (set by /Users/anillakhman/.pyenv/version)
# 2.6.9
# 2.7.12
# 3.1.5
# 3.2.6
# 3.3.6
# 3.4.5
# 3.5.2

# Let's switch to 3.1.5
pyenv global 3.1.5

# Check python
python --version
# Python 3.1.5

pyenv versions
# ...
# * 3.1.5 (set by /Users/anillakhman/.pyenv/version)
# ...

# Set pyenv to load our python versions
# Order matters (system first, then our custom versions)
pyenv global system 2.7.12 3.1.5 3.2.6 3.3.6 3.4.5 3.5.2 2.6.9

Switching versions locally

You can also switch the python version you want to use locally (per project) by using a .python-version file at the root of your project.

When you enter this directory, pyenv will load the python version’s specified in your .python-version.

You can set this up manually or via the command line like so:

# switch to a working dir
cd ~/Sites/some-project/

# Show the current version
pyenv which python
# /usr/local/bin/python

python --version
# Python 2.7.11

# Create a local pyenv
pyenv local 3.2.6
# created a `.python-version` file with content:
# 3.2.6

# We changed python version for this directory only
python --version
# Python 3.2.6

# Globally, we're still using our default `system`
cd .. && python --version
# Python 2.7.11

Troubleshootings

on mac, failed to import sqlite3

CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install -v 3.4.7
# https://github.com/pyenv/pyenv/issues/108#issuecomment-359161050