There's a global option require-virtualenv
to require a virtual environment when operating pip
.
Several ways to enable this (pick one):
As configuration option (which has my preference) like this, in e.g. ~/.config/pip/pip.conf
or /etc/pip.conf
:
[global]
require-virtualenv = True
You can also run this command to modify/create the configuration
file for you:
pip config set global.require-virtualenv True
Use the environment variable PIP_REQUIRE_VIRTUALENV
and set it to value true
.
Directly using the --require-virtualenv
command line option.
If you would then attempt to install packages outside of a virtualenv, you'll see this error:
ERROR: Could not find an activated virtualenv (required).
If you need to override this option temporarily for upgrading pip or installing virtualenv on older Python versions, you can prepend the command with PIP_REQUIRE_VIRTUALENV=false
.
N.B.: This option appears to be missing from the --help
output and docs as a whole in older pip versions (< 22.0), but it's working just fine for me. Tested with 20.3.4 as latest version on Python 2.7.x.
Sidenote: PEP 704 (Draft at the time of writing) is a proposal to "[...] recommends that package installers like pip require a virtual environment by default on Python 3.13+".
pip install
will require root privileges so you are forced to use--user
flag and inside the venv,pip install --user
will fail because the user site is not accessible.