python-3.xinstallationpippackagepython-venv

Getting 'externally-managed-environment' error when trying to install with pip, DESPITE being in a virtual environment


I'm trying to install a package (pytictoc) using Pip 23.2.2. I'm using Python 3.11, and my OS uses a EXTERNALLY-MANAGED marker file to protect the system installation, so I want to use a virtual environment to avoid the well-known error message.

I follow these steps:

  1. Run python3 -m venv env to create a directory called env for my virtual environment.
  2. Then, within that directory, I run source bin/activate to activate the virtual environment
  3. Ensure that the virtual environment is indeed running; (env) should appear at the start of the current line, and any subsequent lines.
  4. Run python -m pip install pytictoc to install the pytictoc package to the virtual environment

However, I still get the error message. Why?

In my research I learned about the --break-system-packages flag, but this seems to be for cases where the user is not using a virtual environment. For my use case, I must install the package in a manually managed virtual environment, not system-wide and not using other tools like Pipx or Conda.

Additional debugging information requested in comments:

$ type -a python
python is aliased to `/usr/bin/python3.11'
python is /~/env/bin/python
python is /usr/bin/python
python is /bin/python

Solution

  • You have python aliased (in your shell) to /usr/bin/python3.11. So when you run python -m pip in command line you actually run global pip, not the pip from the venv, and the global pip complains about "externally managed environment".

    When you activate a virtual environment you should unalias python; you can insert unalias python python3 into activate script. Or always run venv/bin/python -m pip with absolute or relative path.