Why is the PYTHONPATH different when running Python with and without sudo?

风格不统一 提交于 2020-06-27 14:44:30

问题


There's something wrong with my OSX system and python that no amount of googling has fixed. I've uninstalled all traces of python except the system python package with OSX that I'm not supposed to uninstall, and then started afresh with a new python from python.org, and installed pip.

Now...not sure if this particular behavior below is part of the issue, but it seems strange to me:

I ran python twice. Once with sudo and once without. Without sudo, I can't access pip. What's going on?

$ sudo /Library/Frameworks/Python.framework/Versions/2.7/bin/python
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pip
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pip

However...

$ /Library/Frameworks/Python.framework/Versions/2.7/bin/python
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pip
>>>

I've already referred to: sudo python runs old python version

I have nothing in my .bash_profile, or anything in any other profiles.

All I've done is the following:

export PYTHONPATH=/lib/python2.7/site-packages/

ls $PYTHONPATH returns:

_markerlib          pip             pkg_resources.pyc       setuptools-8.0.1.dist-info  virtualenv.pyc
easy_install.py         pip-1.5.6.dist-info     setuptools          virtualenv-1.11.6.dist-info virtualenv_support
easy_install.pyc        pkg_resources.py        setuptools-7.0.dist-info    virtualenv.py

which pip returns:

/bin/pip

回答1:


sudo overrides your export. It's the same Python (as you can easily tell from the version information it prints) but it runs with a different (system default) PYTHONPATH.

This is one of the jobs of sudo; it sanitizes the environment to safe defaults. You may be able to tweak this, but the real question is, what are you trying to accomplish? If you need to run as root with a particular environment, set up a virtualenv and/or write a wrapper script which sets things up before dispatching Python.




回答2:


What do you get when you compare the output of which pip and sudo which pip? On my system I get different outputs. If you do, I'm not sure how to fix that, but you could try to force the sudo'd python to look in the correct directory:

import sys
sys.path.insert(0, '/lib/python2.7/site-packages/')

import pip


来源:https://stackoverflow.com/questions/27466862/why-is-the-pythonpath-different-when-running-python-with-and-without-sudo

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