How to Install Python on Ubuntu

Ubuntu, a robust and widely adopted Linux distribution, serves as an excellent platform for Python development. Its flexibility and extensive package repositories make it a preferred choice for developers, data scientists, and hobbyists alike. Whether you are looking to build web applications, analyze data, automate tasks, or delve into machine learning, having Python installed and configured correctly on your Ubuntu system is the foundational step. This guide will walk you through the essential methods for installing Python on Ubuntu, ensuring you have a smooth and efficient development environment.

Understanding Python Versions on Ubuntu

Ubuntu often comes with a default version of Python pre-installed. However, the specific version can vary depending on the Ubuntu release. Modern development practices, particularly in fields like data science and AI, often necessitate newer Python versions to leverage the latest features, performance enhancements, and library compatibility. Understanding how to manage multiple Python versions is crucial for project isolation and compatibility.

Identifying the Default Python Version

Before installing any new versions, it’s beneficial to know what Python is already available on your system. Open your terminal (Ctrl+Alt+T) and execute the following commands:

python --version
python3 --version

The python command typically points to Python 2 on older Ubuntu versions, while python3 will point to the default Python 3 installation. It’s essential to be aware of which command invokes which Python interpreter, as this distinction can affect how you run scripts and install packages.

The Importance of Python 3

While Python 2 was a staple for many years, its end-of-life in January 2020 means that most new development and ongoing projects are focused on Python 3. Python 3 introduces numerous improvements, including better handling of Unicode, cleaner syntax, and significant performance optimizations. For any new development, it is highly recommended to use Python 3.

Managing Multiple Python Versions

For complex projects or when working with diverse libraries that might have conflicting dependencies, managing multiple Python versions becomes a necessity. Tools like pyenv or using Python’s built-in venv module are invaluable. However, for a straightforward installation, focusing on the system’s default or a specific, newer version is often sufficient. This guide will focus on installing specific, up-to-date Python versions directly from Ubuntu’s repositories or source.

Installing Python from Ubuntu’s Official Repositories

Ubuntu’s Advanced Packaging Tool (APT) is the primary method for installing software. It allows for easy installation, removal, and management of packages. For Python, APT provides access to various versions, making it the most straightforward approach for most users.

Updating Package Lists

Before installing any new software, it’s good practice to update your system’s package lists. This ensures that you are aware of the latest available versions of packages. Open your terminal and run:

sudo apt update

This command fetches the latest information about available packages from the configured software sources.

Installing the Latest Python 3

To install the latest stable version of Python 3 available in Ubuntu’s default repositories, use the following command:

sudo apt install python3

If you need to install Python 3 along with its development headers and common utilities (often required for compiling certain Python packages from source), you can use:

sudo apt install python3-dev python3-pip python3-venv
  • python3-dev: Contains header files and static libraries that are necessary for building Python extensions.
  • python3-pip: The package installer for Python. It allows you to install and manage additional Python packages.
  • python3-venv: Provides support for creating lightweight “virtual environments” in Python.

After installation, you can verify the installed version using python3 --version.

Installing Specific Python 3 Versions (if available in repositories)

While apt install python3 usually gets you the latest version supported by your Ubuntu release, sometimes you might need a specific minor version. Ubuntu’s repositories may contain specific versions like python3.9, python3.10, etc. You can check for their availability with:

apt search python3.

If a specific version, say Python 3.10, is available, you can install it as follows:

sudo apt install python3.10

And then install its associated pip and venv modules:

sudo apt install python3.10-dev python3.10-pip python3.10-venv

You would then invoke this version using python3.10.

Installing Pip

Pip is the de facto package manager for Python. It’s essential for installing third-party libraries and frameworks. When you install python3-pip as shown above, pip for Python 3 is automatically installed. You can verify its installation and version:

pip3 --version

If pip3 is not found, you can install it directly:

sudo apt install python3-pip

Installing Virtual Environments

Virtual environments are a best practice in Python development. They allow you to create isolated Python environments for different projects, preventing dependency conflicts.

To install the venv module for Python 3:

sudo apt install python3-venv

Once installed, you can create a virtual environment for your project:

  1. Navigate to your project directory:
    bash
    cd /path/to/your/project
  2. Create a virtual environment (e.g., named myenv):
    bash
    python3 -m venv myenv
  3. Activate the virtual environment:
    bash
    source myenv/bin/activate

Your terminal prompt will change to indicate that the virtual environment is active. You can now install packages within this isolated environment using pip install <package_name>. To deactivate, simply type deactivate.

Compiling Python from Source

While installing from repositories is convenient, compiling Python from source offers the utmost flexibility. This method allows you to install the absolute latest version, customize build options, and install it in a specific location without interfering with the system’s default Python installation. This is particularly useful for advanced users or when a specific, bleeding-edge version is required.

Prerequisites for Compiling

Before you can compile Python from source, you need to install essential build tools and libraries. Open your terminal and run:

sudo apt update
sudo apt upgrade
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget

  • build-essential: Provides necessary tools like gcc and make for compiling software.
  • zlib1g-dev, libncurses5-dev, libgdbm-dev, libnss3-dev, libssl-dev, libreadline-dev, libffi-dev: These are development libraries that Python often depends on for various functionalities (compression, terminal control, database interactions, security, etc.).

Downloading the Python Source Code

Visit the official Python website (python.org) to find the download link for the desired Python version. For example, to download the source code for Python 3.11.4:

cd ~ # Navigate to your home directory
wget https://www.python.org/ftp/python/3.11.4/Python-3.11.4.tgz

Replace 3.11.4 with the specific version you wish to download.

Extracting and Configuring the Source Code

Once the download is complete, extract the archive:

tar -xf Python-3.11.4.tgz

Navigate into the extracted directory:

cd Python-3.11.4

Next, configure the build. It’s highly recommended to use the --enable-optimizations flag, which enables profile-guided optimizations, and --with-ensurepip=install to ensure pip is installed. You can also specify a custom installation prefix using --prefix. For instance, to install in /opt/python/3.11.4:

./configure --enable-optimizations --with-ensurepip=install --prefix=/opt/python/3.11.4

If you don’t specify --prefix, it will typically install in /usr/local, which is also a common location for manually compiled software.

Compiling and Installing

Now, compile the Python source code. The make -j $(nproc) command compiles in parallel using all available CPU cores, significantly speeding up the process.

make -j $(nproc)

After compilation, install Python using make altinstall. It’s crucial to use altinstall rather than install to prevent overwriting the system’s default Python binary.

sudo make altinstall

If you specified a --prefix earlier, the installation will go to that location. Otherwise, it will be in /usr/local/bin.

Verifying the Installation

To verify the installation, check the version of the newly installed Python. If you installed to a custom prefix, you might need to add its bin directory to your PATH or execute it directly.

If installed in /opt/python/3.11.4:

/opt/python/3.11.4/bin/python3.11 --version

If installed in /usr/local:

/usr/local/bin/python3.11 --version

You should see the version number you compiled. Pip will also be installed at the corresponding bin directory.

Using pyenv for Advanced Python Version Management

For developers who frequently switch between projects requiring different Python versions, pyenv is an indispensable tool. It allows you to install and manage multiple Python versions side-by-side without interfering with the system’s Python.

Installing pyenv

The recommended way to install pyenv is using the pyenv-installer script.

First, install pyenv‘s dependencies (similar to compiling from source):

sudo apt update
sudo apt install -y make build-essential libssl-dev zlib1g-dev libbz2-dev 
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev 
xz-utils tk-dev libffi-dev liblzma-dev python3-openssl git

Then, install pyenv itself:

curl https://pyenv.run | bash

This script will clone the pyenv repository and set up the necessary environment variables. It will output instructions on how to add pyenv to your shell’s configuration file (e.g., ~/.bashrc, ~/.zshrc). Follow these instructions carefully. Typically, you’ll need to add lines like these to your ~/.bashrc:

export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"

After modifying your ~/.bashrc, reload your shell configuration:

source ~/.bashrc

Installing Python Versions with pyenv

Now you can install any Python version:

  1. List available versions to install:
    bash
    pyenv install --list
  2. Install a specific version (e.g., Python 3.10.9):
    bash
    pyenv install 3.10.9

    This will download, compile, and install Python 3.10.9 in ~/.pyenv/versions/.

Setting Python Versions

pyenv allows you to set Python versions globally, locally for a directory, or as a shell-specific override.

  1. Global Version: Sets the default Python for your user.
    bash
    pyenv global 3.10.9
  2. Local Version: Sets the Python version for the current directory and its subdirectories. This is often the most useful for project-specific Python environments.
    bash
    cd /path/to/your/project
    pyenv local 3.10.9

    This creates a .python-version file in your project directory.
  3. Shell Version: Temporarily sets the Python version for the current shell session.
    bash
    pyenv shell 3.10.9

After setting a version, verify it:

python --version

Installing Pip and Virtual Environments with pyenv

When you install Python versions using pyenv, pip is automatically included and associated with that specific Python installation. You can activate the environment and use pip as usual.

For managing virtual environments with pyenv, you can use the pyenv-virtualenv plugin, which integrates seamlessly with pyenv.

This guide provides a comprehensive overview of installing Python on Ubuntu, catering to various needs from basic installations to advanced version management. By following these steps, you can ensure a robust and adaptable Python development environment on your Ubuntu system.

Leave a Comment

Your email address will not be published. Required fields are marked *

FlyingMachineArena.org is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. Amazon, the Amazon logo, AmazonSupply, and the AmazonSupply logo are trademarks of Amazon.com, Inc. or its affiliates. As an Amazon Associate we earn affiliate commissions from qualifying purchases.
Scroll to Top