Installing Python packages using pip on Ubuntu 24.04

Posted . Visible to the public.

Ubuntu 24 added some guarding for Python packages which no longer allows installing applications through pip on system level. Instead, you are presented with this error message:

error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.
    
    See /usr/share/doc/python3.12/README.venv for more information.

As the error says, if your desired application is available as an Ubuntu package, you may install it through apt.
If you need to install through pip (e.g. because there is no Ubuntu package, or if you need a more recent version), you must set up a virtual Python environment for it. Here is how.

  1. Install Python on your system
    sudo apt install python3 python3-pip python3-venv python-is-python3
    
  2. Create a virtual environment
    python -m venv ~/.venvs/your-environment-name
    
  3. Source that environment into your Bash
    source ~/.venv/your-environment-name/bin/activate
    
    Your Bash prompt should now be prefixed with (your-environment-name).
  4. Install package
    pip install your-package-name
    
  5. Binaries from installed packages should now be available, as long as you use your virtual environment.
    (They are located in ~/.venv/your-environment-name/bin/).

To leave your virtual environment, you may call deactivate.

To enter your venv again later, you must source it again, as described above.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2025-02-06 10:20)