---
title: "Changing Python versions"
date: "2015-02-12"
category: "python"
slug: "changing-python-versions"
---

## Overview

Recent [[determining-platform-version]] support multiple Python interpreters using [pyenv](https://github.com/yyuu/pyenv). pyenv enables seamless switching between Python versions and manages version-specific [[installing-packages]].

## Basics

All commands are run from the [[accessing-terminal]].

### Listing Available Versions

Use `pyenv versions` to see installed Python interpreters:

`[myadmin@sol ~]$ pyenv versions system 2.7.8 * 3.3.5 (set by /home/myadmin/.python-version) 3.4.1`

- `system` is the default system interpreter used when pyenv is not active
- `2.7.8`, `3.3.5`, and `3.4.1` are additional interpreters installed under `/.socket/python/versions`

### Selecting a Version

Versions are set per-directory and inherited by all child directories using `pyenv local`:

`[myadmin@sol ~]$ pyenv version 3.3.5 (set by /home/myadmin/.python-version) [myadmin@sol ~]$ cd /var/www/ [myadmin@sol www]$ pyenv local system [myadmin@sol www]$ pyenv version system (set by /var/www/.python-version) [myadmin@sol www]$ cd ~/test [myadmin@sol ~/test]$ pyenv version 3.3.5 (set by /home/myadmin/.python-version)`

Versions are controlled by a `.python-version` file. pyenv ascends each parent directory until it finds this file or reaches root (`/`). If no control file is found, the system Python interpreter is used.

You can organize projects by Python version using a shared parent directory:

www       <-- NO .python-version
|-- proj3 <-- .python-version (3.3.5)
| |-- mydjango  (3.3.5)
| \`-- flask     (3.3.5)
\`-- proj2 <-- .python-version (2.7.5)
  |-- newdjango (2.7.5)
  \`-- mezzanine (2.7.5)

### Package Locations

Packages are installed using [[installing-packages]] as normal. They are stored under `/usr/local/lib/python/_<MAJOR>_._<MINOR>_._<PATCH>_` using [semantic versioning](http://www.semver.org) to avoid conflicts. However, binaries installed under /usr/local/bin may conflict if different package versions install different binaries. Use [pyenv-virtualenv](https://github.com/yyuu/pyenv-virtualenv#usage) + [virtualenv](https://virtualenv.pypa.io/en/latest/) to isolate packages that share the same Python interpreter.

## Caveats

### Shebangs

Shell or FastCGI scripts typically begin with `#!/usr/bin/python`, which points to the system version and bypasses pyenv. Change this to `#!/usr/bin/env python` to use the pyenv-managed interpreter.

## See Also

- [pyenv](https://github.com/yyuu/pyenv) on GitHub
- [virtualenv](https://virtualenv.pypa.io/en/latest/) -- manage same Python version with different package versions
