Skip to content

pyenv

Install pyenv

1
2
3
$ sudo apt-get install -y make build-essential git libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev

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

Also, add the following to your ~/.bashrc or ~/.zshrc:

1
2
3
4
5
# PyEnv
export PATH="${HOME}/.pyenv/bin:${PATH}"
eval "$(${HOME}/.pyenv/bin/pyenv init --path)"
eval "$(${HOME}/.pyenv/bin/pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Cheatsheet

Main usage is:

  • Install a new Python version
  • Create a new virtualenv using this version
  • Make your project use this virtualenv
  • Install dependencies / run your project inside this virtualenv
1
2
3
4
5
6
7
$ pyenv install 3.12.1
$ pyenv rehash
$ pyenv virtualenv 3.12.1 my-project
$ cd ~/workspace/my-project
$ pyenv local my-project
$ python --version
# Python 3.12.1

pyenv install

List available remote Python versions you can install:

$ pyenv install -l

Install Python 3.9.12:

$ pyenv install 3.9.12
$ pyenv rehash

pyenv versions

List locally installed versions:

$ pyenv versions

pyenv global

Set the default Python version system-wide:

$ pyenv global 3.12.1

pyenv shell

Override the version for the current shell session only (takes precedence over global and local):

$ pyenv shell 3.10.0
$ pyenv shell --unset

pyenv local

Set the version for the current directory. Creates a .python-version file — pyenv reads it automatically whenever you cd into the directory.

1
2
3
4
$ pwd
# ~/workspace/my-project
$ pyenv local my-pyenv-virtualenv-name   # use a virtualenv
$ pyenv local 3.12.1                     # or a plain Python version

Unset:

1
2
3
$ pyenv local --unset
# or
$ rm .python-version

pyenv virtualenv

List locally created virtualenvs:

$ pyenv virtualenvs

Create a new virtualenv:

1
2
3
4
# From system's Python version with name `my-project`:
$ pyenv virtualenv my-project
# From a given Python version:
$ pyenv virtualenv 3.9.12 my-other-project

Delete an existing virtualenv:

$ pyenv uninstall my-project

pyenv which / pyenv exec

1
2
3
4
5
6
7
8
# Show the full path of a binary resolved by pyenv
$ pyenv which python
# ~/.pyenv/versions/my-project/bin/python

$ pyenv which pip

# Run a command with a specific version without activating it
$ pyenv exec python -c "import sys; print(sys.version)"

Upgrade pyenv

1
2
3
$ pyenv update    # requires pyenv-update plugin (installed by pyenv-installer)
# or manually:
$ cd $(pyenv root) && git pull