Python, a programming language that enjoys immense popularity worldwide, is versatile and can be used to develop a wide range of applications, from simple scripts to intricate machine-learning algorithms. Its syntax is simple and easy to learn, making it a preferred choice for both beginners and seasoned developers.
This guide will walk you through the process of installing Python from its source code on Ubuntu 22.04. The instructions provided here are also applicable to other Ubuntu-based distributions like PopOS, Kubuntu, Linux Mint, and Elementary OS.
Ubuntu 22.04 comes with Python 3 preinstalled. To verify the Python version on your system, use the following command:
The output should resemble:
If you require different or multiple versions of Python on your system, you’ll need to compile it from the source.
Compiling Python from the source code offers the advantage of installing the latest Python version and tailoring the build settings to your needs. Nevertheless, it’s essential to note that this approach doesn’t provide the convenience of managing your Python installation through the apt package manager.
As of the writing of this guide, Python’s most recent major release is version 3.12, featuring substantial performance improvements and introducing various new elements. These additions encompass new standard library modules, integrated functionalities, fresh syntax, and more.
Here’s how to compile Python 3.12 from the source:
Install necessary libraries and dependencies:
sudo apt update
sudo apt install build-essential zlib1g-dev libgdbm-dev libffi-dev libncurses5-dev libnss3-dev libssl-dev libreadline-dev libsqlite3-dev wget libbz2-dev
Now follow the steps below:
- Download the source code:
Use the wget command to download the latest release’s source code from the Python download page.
- Extract the archive:
tar -xf Python-3.12.0.tgz
- Configure command:
Proceed to the directory containing the Python source code and execute the configure command. This script verifies the existence of all necessary dependencies on your system.
The Python binary can be optimized using the –enable-optimizations option, but this optimization process may result in a slower build.
- Build process:
Start the build process with:
make -j 12
To speed up the build process, adjust the value of -j to match the number of processor cores. You can determine the core count by running the command nproc.
Once the build process is complete, install the Python binaries with:
sudo make altinstall
We opt for altinstall over install to prevent the latter from replacing the existing python3 binary in the system.
You’ve now successfully installed the latest version of Python on your system. To verify your installation, type:
The output should display your Python version:
If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.