Fixing the Externally-Managed-Environment Error in Pip
Package managers are used to install, remove, and manage software packages, usually for a system or programming language. For instance, pip is the default package manager for the Python programming language. However, issues arise when another package manager is also in use for the same purpose.
In this tutorial, we learn how to fix the externally-managed-environment error when installing a package with pip.
Fixing the Externally-Managed-Environment Error in Pip
1. What Is the Externally-Managed-Environment Error?
Installing a package globally with pip may cause package and version conflicts for systems that rely on Python. For this reason, the externally-managed-environment error exists.
This error occurs when the system package manager is managing Python packages. It arises when pip installs outside of a virtual environment and a marker file, EXTERNALLY-MANAGED, exists in Python’s stdlib directory:
$ ls /usr/lib/python3.11
..
enum.py
EXTERNALLY-MANAGED
filecmp.py
...
To avoid this error, we must install the Python package using the system package manager or a virtual environment.
2. Installing With apt
In most cases, the easiest method of getting around the externally-managed-environment error is installing the Python package using the system package manager.
For instance, to install the arrow
package on Ubuntu:
$ sudo apt install python3-arrow
Now, arrow
is installed globally, and updating our system updates this package as well.
3. Installing With venv
While installing using the system’s package manager may be convenient, it also has its limitations such as limited number of package versions available and less up-to-date packages. To get around these restrictions, we can use venv
to create a virtual environment.
3.1. Creating Virtual Environment
First, install venv
:
$ sudo apt install python3-venv
Then, create and activate your virtual environment:
$ python3 -m venv ~/myvirtualenv
$ source myvirtualenv/bin/activate
(myvirtualenv) $
3.2. Installing Packages in Virtual Environment
After activating the virtual environment, install the necessary packages using pip:
(myvirtualenv) $ pip install 'arrow'
Now, you can also install packages from a requirements.txt
file:
$ echo 'url-normalize' > requirements.txt
$ echo 'chess' >> requirements.txt
$ echo 'requests' >> requirements.txt
$ pip install -r requirements.txt
Once done, deactivate the virtual environment:
$ deactivate
4. Using pipx
pipx is a utility for installing Python packages in isolated environments, avoiding the “externally-managed-environment” error.
First, install pipx:
$ sudo apt install pipx
Then, use pipx to install packages:
$ pipx install openai
Conclusion
In this tutorial, we covered what the externally-managed-environment error is and how to overcome it using three different methods: using the system package manager, creating a virtual environment with venv, and using pipx.