Files
knowledge-base/docs/python/pip-env-vars.md

3.2 KiB

Why pip install Fails: Python Externally Managed Environments

If you are seeing the error error: externally-managed-environment on Linux (Debian 12, Ubuntu 24.04, etc.), this guide explains why it happens and how to fix it correctly.

1. The "Why": Protecting Your Operating System

This error is a safety feature introduced by PEP 668.

On Linux, Python is part of the Operating System. Critical system tools (like apt, dnf, network managers, and display servers) rely on specific versions of Python libraries installed by the OS package manager.

  • The Old Way: pip allowed you to install/upgrade packages globally. This often overwrote versions the OS needed, leading to "broken" systems where system updates or tools would fail.
  • The New Way: pip now detects if the environment is managed by the OS and refuses to touch it unless you use an isolated environment.

2. The Solution: Three Ways to Install Packages

There are three correct ways to install Python packages depending on your goal.

Method A: For Development (Projects & Scripts)

Best for: Writing code, learning Python, or running specific projects. Tool: venv (Virtual Environment)

This creates a self-contained folder (.venv) with its own Python and libraries, completely isolated from the system.

  1. Create the environment (inside your project folder):

    python3 -m venv .venv
    

    (Note: If this fails, run sudo apt install python3-venv first).

  2. Activate the environment:

    source .venv/bin/activate
    

    (Your terminal prompt should now show (.venv)).

  3. Install your package:

    pip install pyusb
    

To exit the environment later, just type deactivate.

Method B: For Standalone Applications

Best for: CLI tools you want to run from anywhere (e.g., youtube-dl, black, ansible). Tool: pipx

pipx creates a managed virtual environment for each application automatically and links the executable to your global path.

  1. Install pipx (once):
    sudo apt install pipx
    pipx ensurepath
    
  2. Install the tool:
    pipx install package-name
    

Method C: For System-Wide Libraries

Best for: When a script must use the system Python and you don't need a specific newer version. Tool: apt (or your OS package manager)

The OS maintainers package Python libraries that are guaranteed to be compatible with your system.

  1. Search for the package:
    apt search python3-pyusb
    
  2. Install it:
    sudo apt install python3-pyusb
    

3. Summary Cheat Sheet

Goal Do NOT run DO Run
Coding/Project pip install pyusb python3 -m venv .venv (then pip install)
Command Line Tool pip install youtube-dl pipx install youtube-dl
System Requirement sudo pip install pyusb sudo apt install python3-pyusb

⚠️ Warning: The error message mentions the flag --break-system-packages. Avoid using this. It allows you to override the safety check, but it carries a high risk of breaking your OS updates or system tools in the future.