17

I really hate running something like make and then be surprised by pip installing a load of packages because I forgot to activate my virtualenv.

Is there any way to force pip to prompt / warn me that I'm not in some virtualenv?

Mikhail
  • 8,692
  • 8
  • 56
  • 82

4 Answers4

33

Taken from http://docs.python-guide.org/en/latest/dev/pip-virtualenv/

You need to set a environmental variable PIP_REQUIRE_VIRTUALENV

Best practice would be to place it in your autostart file (.bash_profile or similar)

export PIP_REQUIRE_VIRTUALENV=true

To install the package globally, you can then run PIP_REQUIRE_VIRTUALENV="" pip ... or create a command gpip, also in the autostart file:

gpip() {
    PIP_REQUIRE_VIRTUALENV="" pip "$@"
}
zalun
  • 4,619
  • 5
  • 31
  • 33
4

Make a note that pip version 20.2.3 from Python 3.6 requires PIP_REQUIRE_VIRTUALENV=false rather than PIP_REQUIRE_VIRTUALENV="" to install global dependencies.

Kevin
  • 143
  • 1
  • 7
3

You can enforce this by passing a flag to pip:

python3 -m pip --require-virtualenv install <some-package>

Or by setting a configuration option:

python3 -m pip config set global.require-virtualenv True
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
0

If you have gotten in the habit of never typing sudo beforehand and follow up critical commands with sudo !! then you can do this script to follow up restricted pip commands with pipdo !!

--user is used to not clobber you global install (which is also the reason that we use PIP_REQUIRE_VIRTUALENV What is the purpose "pip install --user ..."?

More explanation of why you may want install without an virtualenv, but you still may want to protect yourself against install into your system python. https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim#simple-setup

# don't let pip work without using virtualenvs
export PIP_REQUIRE_VIRTUALENV=true
# allow to overcome the above with pipdo !!
function pipdo {
    case "$@" in
      *install*--user*)
        PIP_REQUIRE_VIRTUALENV=false $@
        ;;
      *install*)
        echo 'Remember to `pip install --user`'
        ;;
      *)
        PIP_REQUIRE_VIRTUALENV=false $@
        ;;
    esac
}
Zak
  • 936
  • 10
  • 19