【问题标题】:pip with virtualenv requires sudo带有 virtualenv 的 pip 需要 sudo
【发布时间】:2015-06-22 18:22:03
【问题描述】:

我在 OSX 上,通过 virtualfish 设置了一个名为 ds-mapreduce-env 的 python virtualenv。在我的项目目录中激活venv 后,看起来就像选择了正确的pippython

~/d/ds-mapreduce (venv) master ➜ which pip
/Users/cody/.virtualenvs/ds-mapreduce-env/bin/pip
~/d/ds-mapreduce (venv) master ➜ which python
/Users/cody/.virtualenvs/ds-mapreduce-env/bin/python

但是当我运行pip install 时,它并没有按预期安装到虚拟环境中。但是,当我使用 sudo 时,它确实如此。

~/d/ds-mapreduce (venv) master ➜ pip install geonamescache
Requirement already satisfied (use --upgrade to upgrade): geonamescache in /usr/local/lib/python2.7/site-packages

~/d/ds-mapreduce (venv) master ➜ sudo pip install geonamescache
The directory '/Users/cody/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/cody/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting geonamescache
Installing collected packages: geonamescache
Successfully installed geonamescache-0.18

我猜这是某种权限问题,但我想不通。我安装了pythonbrew install pythonvirtualfishpip install virtualfish。我尝试删除并重新安装没有效果。

我的解决方案

我的问题是我的PYTHONPATH。我的PYTHONPATH 前面有/usr/local/lib/python2.7/site-packages。删除它可以解决问题!

【问题讨论】:

  • 您是否以 root 身份创建了 virtualenv? (root是否拥有文件夹“/Users/cody/.virtualenvs/ds-mapreduce-env”)
  • 不以root身份:drwxr-xr-x 7 cody staff 238B Jun 22 12:23 ds-mapreduce-env
  • 嗨科迪。我在这里的回答是否有助于解决您的问题?

标签: python pip virtualenv sudo fish


【解决方案1】:

第一步是卸载全局安装的包:

pip uninstall -y geonamescache

通过检查/usr/local/lib/python2.7/site-packages/ 确认它已被完全删除。如果没有,请手动移除您在那里找到的任何相关碎屑。

下一步是更好地将虚拟环境的site-packages 与全局site-packages 隔离开来。将以下内容添加到~/.config/fish/config.fish

set -x PIP_REQUIRE_VIRTUALENV "true"

如果您打开一个新的终端会话,如果您在没有激活虚拟环境的情况下运行pip install geonamescache,您现在应该会收到一个错误——这正是我们想要的。通过vf new ds-mapreduce-env 创建并激活一个新的虚拟环境并再次尝试同样的pip install geonamescache 调用,包应该安装到虚拟环境中。

由于这会阻止您将任何内容安装到全局 site-packages 中,您可能需要设置一个别名,以允许您覆盖此隔离并执行全局 pip 操作。将以下函数添加为~/.config/fish/functions/gpip.fish

function gpip -d "Manage globally-installed Python packages"
    env PIP_REQUIRE_VIRTUALENV="" pip $argv
end

有了这些,您可以(例如)通过以下方式升级您的全局包:

gpip install --upgrade setuptools pip wheel virtualenv

以上大部分问题已经通过Tacklebox + Tackle(查找pip 插件)解决,这些项目旨在轻松为您的fish 环境添加增强功能。

【讨论】:

  • 感谢贾斯汀的回答。我没有尝试过这个解决方案,因为我自己解决了这个问题(参见上面的编辑)。
  • 喜欢将 pip 限制为 virtualenv 的开关。