Install an Alternative Python Version the Other Way

Auther:

Lin

Version:
1.0

Build Dependencies

Before starting, make sure you have all the necessary build dependencies installed. If you're missing some libraries before you build the new python, you'll find certain features not working and you'll have to rebuild it. And you only find out after the lengthy make process.

For rasberry pi (buster):

sudo apt-get install libffi-dev libbz2-dev liblzma-dev \
    libsqlite3-dev libncurses5-dev libgdbm-dev zlib1g-dev \
    libreadline-dev libssl-dev tk-dev build-essential \
    libncursesw5-dev libc6-dev openssl libgdbm-compat-dev

For Ubuntu (bionic):

sudo apt-get install build-essential tk-dev libncurses5-dev \
    libncursesw5-dev libreadline-dev libdb5.3-dev libgdbm-dev \
    libsqlite3-dev libc6-dev libssl-dev libbz2-dev libexpat1-dev \
    liblzma-dev zlib1g-dev libffi-dev uuid-dev

export TCLTK_LIBS="-ltk8.6 -ltkstub8.6 -ltcl8.6"
export TCLTK_CFLAGS="-I/usr/include/tcl8.6"

Download the source tarball

This should be easy to find on Python's source download page. At the time of this writing the latest version is 3.12.4.

$ cd /path/to/Downloads
$ tar xvf Python-3.12.4.tar.xz
$ cd Python-3.12.4

./configure, make, build and install

Run these commands in the directory extracted from the tarball:

./configure --prefix=/usr/local --enable-optimizations \
    --with-ensurepip=install
make -j $(nproc --all)
sudo make install

Some people suggesting use make altinstall instead of make install, which in fact just skips creating the python link (make bininstall) and manual pages links (make maninstall). Since I have --prefix in place, I will use make install.

If you installed all the build dependencies correctly above, everything should proceed without any errors. You now have a shiny new version of Python to play with. You should be able to run the python REPL from the command line.

$ python3.12
Python 3.12.4 (main, Nov  9 2024, 12:33:53) [GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Create a virtual environment

If you're following Python best practices, you're probably creating a new virtual environment for every project. It's easy to create one with your new python version. I'm making a catchall environment to messing around.

$ python3.12 -m venv /opt/certbot/

Include in the $PATH, instead of doing source /opt/certbot/bin/activate every single time.

echo 'export PATH="/opt/certbot/bin:$PATH"' \
    >> /home/$USER/.bashrc

This gives me the ability to test out random libraries without messing up the main installation.