Using Python on Linux & Unix Platforms¶
Virtually every Linux distribution relies heavily on Python for operating system maintenance, package management tools (like apt, dnf, and yum), and system services. This guide covers distribution packages, PEP 668 restrictions, and building Python from source.
Distribution Package Managers¶
Different Linux distributions split Python into modular packages:
PEP 668: The "Externally Managed Environment" Error¶
On modern Linux distributions (Debian 12+, Ubuntu 23.04+, Fedora 38+), running pip install <package> globally outputs an error:
Why Does This Happen?¶
In the past, users running sudo pip install would overwrite system Python libraries maintained by apt or dnf, breaking system utilities. PEP 668 prevents this collision.
The Correct Solutions¶
- For Projects: Always use a project virtual environment:
- For Global CLI Tools (like Black, Ruff, or MkDocs): Use
pipxto install tools into isolated per-application environments:
Compiling Python from Source¶
When you need the latest Python release before your distribution packages it, or need a debug build, compile from source:
1. Install Build Dependencies¶
2. Configure and Compile¶
# Download and unpack release tarball
wget https://www.python.org/ftp/python/3.13.0/Python-3.13.0.tgz
tar -xf Python-3.13.0.tgz
cd Python-3.13.0
# Configure with production optimizations
./configure --enable-optimizations --with-lto
# Compile using all available CPU cores
make -j $(nproc)
3. Install with altinstall¶
Always Use make altinstall, Never make install!
Running sudo make install overwrites the system /usr/bin/python3 binary, breaking your Linux operating system!
sudo make altinstall installs the binary as /usr/local/bin/python3.13 without replacing the system python3 alias:
Verify the installation:
Shebang Conventions & Executable Permissions¶
To make a Python script directly executable from the Linux terminal:
- Add the portable shebang line as the first line of the file:
- Grant execute permissions with
chmod: - Run the script directly: