4

So I was googling an event where pip required sudo privileges,and I came across the following two threads What are the risks of running 'sudo pip'? and Is it acceptable & safe to run pip install under sudo?

The first thread talks about the security risk of running an unknown .py file with pip (makes sense), but from the second one I almost got the impression that there exists a global and local python installation that you should not mix up. I guess it makes it sense that you can have a global installation for all users and then maybe an appended path to local packages for each user, but is this true? (it would also make sense since ubuntu (which I'm using) has dependencies on certain python packages, so having a global root protected python directory would protect these). However, if this is true, I can't find the two separate directories. I tried

import sys 
print(sys.path)

with both sudo and no sudo, and I got the exact same directories.

In any case, I think I'll move to pip virtualenv, but in that case I was wondering, what would happen if I accidentaly forgot to activate the environment and ran an exotic requirements.txt outside? Wouldn't that corrupt my standard user directory I'm trying so hard to keep clean (if that is so, is that revertible? I'm just thinking, it's only forgetting to type one commando, and then your python installation is messed up.)

4

2 回答 2

5

我确实建议始终使用 virtualenv 来满足特定应用程序的特定要求。您作为多个项目的开发人员使用的工具(例如ipdb)可以在系统上全局安装。

请注意,所有 pip 包都是开源的,因此您可以确保著名的 pip 包可能没有恶意代码,但当然可能包含安全漏洞。

为了防止在 virtualenv 之外意外安装 pip 包,您可以将其添加到您的.bashrc

export PIP_REQUIRE_VIRTUALENV=true

然后,当您pip install something在 virtualenv 之外运行时,它将显示一条错误消息:

Could not find an activated virtualenv (required).

如果您仍然希望能够在 virtualenv 之外安装 pip 包,您可以.bashrc像这样添加一个函数:

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

然后你可以运行syspip install something在你的系统上全局安装一些东西。

至于您正在运行的脚本:

import sys 
print(sys.path)

无论您是否使用 sudo 运行它都没有关系,sudo 只会更改您正在执行命令的用户权限,对于这个脚本来说这无关紧要。

于 2015-04-13T22:31:02.617 回答
1

运行sudo pip install <package>会将包安装到系统范围的包集,通常存储在/usr/lib/python2.7/site-packages.

在没有激活 virtualenv 的情况下运行pip install package将尝试将软件包安装到同一个位置,但是因为(如果您的系统配置正确/正确)您将没有对该文件夹的写入权限,安装命令将失败。

如果您绝对必须全局安装,如果可以进行全局安装,通常最好使用分发包,因为这样您可以获得自动更新的好处。但是,正如您所了解的那样,最好不要全局安装软件包,而是使用 virtualenvs

于 2015-04-13T22:22:00.357 回答