Solution to the "error: externally-managed-environment" error in Python.

Author
By Darío Rivera
Posted On in Python

From Ubuntu 23.04 you may encounter a new error in Python due to a change in the package installation policy that prevents packages installed through pip from colliding in any way with those installed with APT.

The error in question is:

error: externally-managed-environment

Solution

To prevent problems with packages from the operating system and Python, it is recommended to use a virtual environment with venv. The first thing you should do is to create a virtual environment. For this, we will install venv.

sudo apt install python3-venv

After this, you must create a virtual environment. You can create as many as you want. The following command uses venv to create the environment in the ".venv" folder where the command was executed.

python3 -m venv .venv

It is recommended to create the virtual environment within each project. This is because each Python project may have different package requirements and Python versions. If you take a look at the created folder, you will see the following:

user@server# ls .venv/
bin  include  lib  lib64  pyvenv.cfg

What you see is a virtual environment with a copy of python and pip. Everything you install after activating that environment will be within that virtual environment. Finally, to activate the created environment, you can use the following command:

source .venv/bin/activate

As an example, if you want to install openai after having activated the environment, you can execute pip as follows:

pip install openai

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.