brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: PIP_REQUIRE_VIRTUALENV stops pip from installing outside a virtual environment

Pip
~/tips/tip-python-pip-require-virtualenv

export PIP_REQUIRE_VIRTUALENV=true

Makes pip refuse to install packages unless a virtual environment is active.

Typing pip install in the wrong terminal tab is the classic way to fill your user or system Python with packages that belonged in a project. pip has a setting that simply refuses to install anything when no virtual environment is active, and I think it should be on by default for anyone who works with venvs.

The command-line flag is --require-virtualenv, but you don’t want to type that every time. The environment variable does the same job, so put it in your ~/.zshrc or ~/.bashrc:

export PIP_REQUIRE_VIRTUALENV=true

Open a new shell and try an install outside a venv:

$ python3 -m pip install requests
ERROR: Could not find an activated virtualenv (required).

Nothing is installed and pip exits with an error code. Activate the project’s venv (source .venv/bin/activate) and the same command works as usual. On my MacBook this is the setting I’d add before anything else, because Homebrew’s Python and the system one make it easy to lose track of which interpreter you’re talking to.

Read-only commands keep working everywhere. In pip’s source, pip list, pip show, pip config, pip cache and a few others are marked to ignore the setting, so you can still look around a global install. It’s the installs and uninstalls that get blocked.

The caveat is the one time you really do want a global install, for example a tool you install with pip install --user. Override the variable for that one command:

PIP_REQUIRE_VIRTUALENV=false python3 -m pip install --user some-tool

The same setting also exists in pip’s config file as require-virtualenv = true under [global], if you prefer that to an environment variable.

Further reading: pip docs: general options (–require-virtualenv), pip docs: configuration, Python docs: virtual environments and packages

More Pip tips urllib3<2 python3 -m pip download -r requirements.txt -d ./wheels python3 -m pip config set global.timeout 60 python3 -m pip index versions requests python3 -m pip download requests==X.Y.Z --no-deps -d ./pkgs All Pip tips (9) All topics

Link