This guide provides a clean and safe method to install Python 3.12 on Ubuntu 20.04 running under WSL2, without touching the system Python.
Linux distros normally have a Python version tied to the distro and used for various admin scripts. You should not expect to follow the latest releases of Python. And don't try to force change it because you could break your OS. If you need newer Python versions for your work, install it in user space.
Linux 20.04 come with python 3.8 which not supported natively to latest version of python (ex. 3.12.x), so by using pyenv will help you install other version of python without touching OS system, and it won't break your system.
If you've previously tried installing Python via the deadsnakes PPA, clean it up first:
sudo rm -f /etc/apt/sources.list.d/deadsnakes*
sudo rm -f /etc/apt/keyrings/deadsnakes.gpg
sudo apt-key del BA6932366A755776 2>/dev/null || true
sudo apt clean
sudo apt updateConfirm cleanup:
grep -r "deadsnakes" /etc/apt/sources.list.d /etc/apt/sources.list || echo "β
 No deadsnakes entries found."These packages are required to compile Python from source:
sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev libbz2-dev      libreadline-dev libsqlite3-dev curl libncursesw5-dev xz-utils tk-dev      libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev gitRun the official installer script:
curl https://pyenv.run | bashThis installs:
pyenvβ version managerpyenv-virtualenvβ for managing environmentspyenv-updateβ for updating pyenv
Add the following lines to the bottom of your ~/.bashrc (or ~/.zshrc if you use zsh):
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"Reload the shell:
source ~/.bashrcCheck available versions:
pyenv install --list | grep " 3\.12"Then install the latest patch release (example: 3.12.7):
pyenv install 3.12.7This step compiles Python from source β it may take several minutes.
pyenv global 3.12.7Verify:
python --version
# Expected: Python 3.12.7pyenv virtualenv 3.12.7 myproject-env
pyenv activate myproject-envDeactivate later with:
pyenv deactivate| Task | Description | 
|---|---|
| Safe installation | Does not modify system Python | 
| Works in WSL2 | Fully compatible | 
| Easily switch versions | pyenv global or pyenv shell | 
| Supports virtualenvs | Isolated environments per project | 
pyenv update
pyenv install --list | grep 3\.12
pyenv install 3.12.x  # latest patch
pyenv global 3.12.xDone! π
You now have a clean Python 3.12 setup using pyenv on WSL2 Ubuntu 20.04.