pyenv lets you install and switch between multiple Python versions on the same server — essential when different projects require different Python versions, similar to NVM's role for Node.js.
Why Not Just Use the System Python?
The system Python (pre-installed on most Linux distributions) is often used by the OS itself for internal scripts — modifying or replacing it directly risks breaking system functionality; pyenv lets you install additional Python versions independently, leaving the system Python untouched.
Step 1 — Install Build Dependencies
sudo apt install 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 -y
pyenv builds Python from source, requiring these development libraries to be present.
Step 2 — Install pyenv
curl https://pyenv.run | bash
Step 3 — Add pyenv to Your Shell Profile
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc
Step 4 — Install a Specific Python Version
pyenv install 3.12.1
Compiles Python from source — can take several minutes depending on your server's CPU.
Step 5 — Set a Global Default Version
pyenv global 3.12.1
Setting a Project-Specific Version
cd myproject
pyenv local 3.11.6
Creates a .python-version file in the project directory — pyenv automatically switches to this version whenever you're in that directory.
Listing Installed and Available Versions
pyenv versions
pyenv install --list
Combining with Virtual Environments
pyenv install 3.12.1
pyenv local 3.12.1
python -m venv venv
source venv/bin/activate
See How to Set Up a Python Virtual Environment Correctly for the broader virtual environment concept — pyenv manages which Python interpreter version is available; virtual environments manage per-project package isolation on top of that.
Using pyenv-virtualenv Plugin (Combining Both Concerns)
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
pyenv virtualenv 3.12.1 myproject-env
pyenv local myproject-env
Combines version and virtual environment management into one unified workflow.
Common Errors
Python installation fails during compilation — usually a missing build dependency; carefully review the specific error for which library is missing and install it, since pyenv's source-build approach is sensitive to a complete build toolchain.
Continue Reading
- How to Set Up a Python Virtual Environment Correctly
- How to Install Python on Ubuntu & Debian
- How to Deploy a Django/Flask Application with Gunicorn and Nginx
Browse more articles in Programming Languages & Runtimes.