We will follow the procedure below to install a version of Python different than the system installed one.
In this system (WSL Debian 11), the distro provided Python is 3.9. We will install a newer release (3.12.3)
- Install required dependencies (follow the python dev guide docs)
# For debian 11, Add the following in /etc/apt/sources.lists:
# deb-src http://deb.debian.org/debian bullseye main
~ → sudo apt-get update
~ → sudo apt-get build-dep python3
~ → sudo apt-get install pkg-config
~ → sudo apt-get install build-essential gdb lcov pkg-config \
libbz2-dev libffi-dev libgdbm-dev libgdbm-compat-dev liblzma-dev \
libncurses5-dev libreadline6-dev libsqlite3-dev libssl-dev \
lzma lzma-dev tk-dev uuid-dev zlib1g-dev libmpdec-dev
- Create a directory to hold the python installations (we will use
~/python. When completed this directory will contain abin/directory where the binaries can be found)
~ → mkdir -p ~/python
- Download the source code (in a different directory, here using
~/Download/) and untar:
Download → wget https://www.python.org/ftp/python/3.12.3/Python-3.12.3.tgz
Download → tar -zxvf Python-3.12.3.tgz
- In the directory with the untarred source code, run
configurespecifying the previously created directory as prefix, and compile:
Download → cd Python-3.12.3/
Python-3.12.3 → ./configure --prefix=$HOME/python
Python-3.12.3 → make
- Install using
make altinstall(NOT make install)
Python-3.12.3 → make altinstall
- The python binary should be now in $HOME:
Python-3.12.3 → cd ~
~ → ls $HOME/python/bin/
2to3-3.12 idle3.12 pip3.12 pydoc3.12 python3.12 python3.12-config
The new python can be used to create a new venv:
~ → ~/python/bin/python3.12 -m venv ~/venv/py3.12
~ → source ~/venv/py3.12/bin/activate
(py3.12) ~ → python --version
Python 3.12.3
Alternatives
References
- Python Developer’s Guide > Getting started > Setup and building > Install dependencies (devguide.python.org)
- Using Python on Unix platforms > Python-related paths and files (docs.python.org)
- cpython README.rst > Installing multiple versions (github.com/python)
- pyenv/pyenv: Simple Python version management (github.com/pyenv)
- Pyenv – lets you easily switch between multiple versions of Python | Hacker News (news.ycombinator.com)