Install pyenv on Ubuntu 22.04
pyenv installs and switches user-level Python versions without replacing Ubuntu's system Python. Do not remove the distribution-provided interpreter because apt and other operating-system tools may depend on it.
Install pyenv
Clone the repository and build its optional native extension:
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
cd ~/.pyenv && src/configure && make -C src
Add the following initialization to ~/.bashrc:
export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
Reload the shell configuration:
. ~/.bashrc
pyenv --version
Configure an optional download mirror
When the official Python download host is slow or unavailable, configure a trusted mirror in ~/.bashrc:
export PYTHON_BUILD_MIRROR_URL_SKIP_CHECKSUM=1
export PYTHON_BUILD_MIRROR_URL=https://registry.npmmirror.com/-/binary/python/
Skipping checksum verification reduces supply-chain protection. Prefer a mirror that publishes compatible checksums, and remove PYTHON_BUILD_MIRROR_URL_SKIP_CHECKSUM when it is not required.
Install build dependencies
sudo apt-get update
sudo apt-get install -y \
build-essential zlib1g-dev libffi-dev libssl-dev \
libbz2-dev libreadline-dev libsqlite3-dev liblzma-dev tk-dev
Additional Python versions may require packages such as libncurses-dev, xz-utils, libxml2-dev, or libxmlsec1-dev.
Install and select Python
pyenv install 3.7.8
Set a version only for the current project directory:
pyenv local 3.7.8
Or set the default version for the current user:
pyenv global 3.7.8
Verify the selected interpreter:
python --version
pyenv which python
pyenv versions
Python 3.7 is end-of-life and should be used only when a legacy project requires it. Prefer a currently supported Python release for new applications.