Disable pip outside of virtual environments

To make sure that pip only runs in a virtual environment you can set the PIP_REQUIRE_VIRTUALENV environment variable to true and pip will never run outside of a virtual env! Simply add export PIP_REQUIRE_VIRTUALENV=true to your .bashrc or .zshrc. Now, each time you try to run pip outside of a virtual env, it will simply refuse to do so:

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

If you want to actually install something outside of a virtual environment, you can temporarily clear that env variable: env PIP_REQUIRE_VIRTUALENV='' pip install request. Why would you ever want to do that? For example, to install the great pipx tool that lets you further isolate your command line Python packages.

You can also create a bash command to install pip packages that ignores this setting:

gpip() {
  PIP_REQUIRE_VIRTUALENV="" pip "$@"
}

Now I no longer have to worry about installing dependencies outside of a virtual environment!