Global and local python installations, and accidentally running a requirements file outside of virtualenv

孤者浪人 提交于 2019-12-05 20:59:23

I would indeed advice to always use virtualenv for requirements specific to a certain application. Tools you use as a developer for multiple projects (something like ipdb) are fine to install globally on the system.

Note that all pip packages are open source, so you have some assurance that famous pip packages are likely not to have malicious code, but could contain security leaks of course.

To prevent accidentally installing a pip package outside a virtualenv, you can add this to your .bashrc:

export PIP_REQUIRE_VIRTUALENV=true

When you then run pip install something outside a virtualenv, it will show an error message:

Could not find an activated virtualenv (required).

If you still want to be able to install pip packages outside a virtualenv, you can add a function in your .bashrc like this:

syspip() {
    PIP_REQUIRE_VIRTUALENV="" sudo pip "$@"
}

Then you can run syspip install something to install something globally on your system.

As for the script you are running:

import sys 
print(sys.path)

It doesn't matter if you run that with sudo or not, sudo only changes the user privileges you are executing the command with, for this script it doesn't matter.

Running sudo pip install <package> will install the package to the system wide set of packages, typically stored somewhere like /usr/lib/python2.7/site-packages.

Running pip install package without a virtualenv activated will attempt to install the package to the same place, but because (if your system is configured sanely/correctly) you won't have write access to that folder, the install command will fail.

It's generally better to use distribution packages if you can for global installs if you absolutely have to install globally, as then you get the benefit of automatic updates. As you've worked out however, it's far better to not install packages globally at all, and use virtualenvs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!