3

Sometimes when working with Python projects one can forget to activate a virtual environment.

Is there a way to get an explicit confirmation when installing Python modules with pip to the global scope instead of a virtual environment?

Aidas Bendoraitis
  • 3,965
  • 1
  • 30
  • 45
  • 1
    Installing in the global scope shouldn't work unless you ran `pip` with `sudo`, which you shouldn't do if you're trying to work in a virtualenv. – jwodder May 16 '16 at 17:46
  • @jwodder If you install Python through Mac OS X's Homebrew, everything is installed to `/usr/local/` and you could `pip install` "globally" without sudo. – kennytm May 16 '16 at 18:36

2 Answers2

1

You can try to wrap pip install, e.g.:

import pip

def install(package):
    pip.main(['install', package])

# Example
if __name__ == '__main__':
    if not hasattr(sys, 'real_prefix'):
        # replace this with your confirmation callback
        print('Warning! installing in global scope!')
    install('argh')

Sources:

Installing python module within code

Python: Determine if running inside virtualenv

Community
  • 1
  • 1
dimid
  • 7,285
  • 1
  • 46
  • 85
0

You could use:

$ pip config set install.require-virtualenv true

but this results in a rather inconvenient error when trying to install without a virtual environment:

ERROR: Could not find an activated virtualenv (required).

I have opened a PR implementing a more user-friendly option (at least in my opinion) to enable a warning instead of an error that also has a prompt to ask whether you'd like to continue or not. If that gets merged then you'll be able to do the following:

$ pip config set install.global-install-warning true
$ pip install -r requirements.txt
WARNING: Could not find an activated virtualenv.
Proceed (y/N)? 
Sujal Singh
  • 532
  • 1
  • 5
  • 14