Back to Tutorials
Python Environment Setup with PyENV
Install and manage multiple Python versions using PyENV and virtual environments on Ubuntu.
PyENV lets you install and switch between multiple Python versions without touching your system Python.
Install Dependencies (Ubuntu 22.04)
bash
sudo apt update
sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev \
libffi-dev liblzma-dev
Install PyENV
bash
curl https://pyenv.run | bash
Add to your shell config (~/.bashrc or ~/.zshrc):
bash
export PYENV_ROOT="$HOME/.pyenv"
command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
Restart your shell:
bash
exec "$SHELL"
Common Commands
bash
# List available Python versions
pyenv install --list
# Install a specific version
pyenv install 3.11.7
# Set global default
pyenv global 3.11.7
# Set local version (per-directory)
pyenv local 3.10.13
# List installed versions
pyenv versions
Using PyENV with Virtual Environments
bash
# Create a virtualenv
pyenv virtualenv 3.11.7 my-project-env
# Activate it
pyenv activate my-project-env
# Set it as the local environment for a directory
cd /path/to/project
pyenv local my-project-env
# Deactivate
pyenv deactivate
# Delete a virtualenv
pyenv virtualenv-delete my-project-env
With pyenv local, the environment activates automatically when you cd into the project directory.