How to Prohibit Global Pip Commands and Only Allow Them in Virtualenv

Nathaniel Mar 08, 2017

Sometime it’s too easy to forget to source bin/activate to activate the virtual environment for your project before running pip install. As a result, you’ll have to spent quite some effort cleaning up the packages you accidentally installed on the system’s native pip.

So, is there a way to automatically reject pip install if there’s no virtualenv detected? The answer is, YES.

Simply add the following lines to .bash_profile (on Mac) or .bashrc (on Ubuntu):

# pip should only run if there is a virtualenv currently activated
export PIP_REQUIRE_VIRTUALENV=true

# use gpip to upgrade global packages
gpip(){
PIP_REQUIRE_VIRTUALENV="" pip "[email protected]"
}

Then reload,

$source ~/.bash_profile From now on, whenever you pip install something, the terminal will automatically check whether there’s an activated virtualenv. If not, you see some error message like this:$ pip install requests
Could not find an activated virtualenv (required).

Disclaimer: This method was NOT invented by me. I learned about it a long time ago but I couldn’t find the original article on Google when my friend asked me for it just now. So I decided to write a post by myself so that it’d be easier to share. Please contact me if you are the inventor.