问题
I am running ipython from sage and also am using some packages that aren't in sage (lxml, argparse) which are installed in my home directory. I have therefore ended up with a $PYTHONPATH of
$HOME/sage/local/lib/python:$HOME/lib/python
Python is reading and processing the first easy-install.pth it finds ($HOME/sage/local/lib/python/site-packages/easy-install.pth) but not the second, so eggs installed in $HOME/lib/python aren't added to the path. On reading the off-the-shelf site.py, I cannot for the life of me see why it's doing this.
Can someone enlighten me? Or advise how to nudge Python into reading both easy-install.pth files?
Consolidating both into one .pth file is a viable workaround for now, so this question is mostly for curiosity value.
回答1:
TL;DR: call site.addsitedir to process .pth files
I'm not sure about OS X, but PYTHONPATH and site package are actually kind of independent where it comes to augmenting sys.path.
Try this:
set PYTHONPATH somehow (OS dependent)
python -c "import sys; print '\n'.join(sys.path); print sys.exec_prefix; print sys.prefix"
python -S -c "import sys; print '\n'.join(sys.path);print sys.exec_prefix; print sys.prefix"
On my linux box, the PYTHONPATH is part of the output both times - even though -S switch in the second run skips importing the site module.
Now, what site.module does is actually taking combinations of (sys.exec_prefix, sys.prefix) and OS dependant prefixes (for linux: lib/python2.7/dist-packages), checks if any of the combinations is an existing directory, and if so processes it (parsing .pth files included)
The code is in site.py module - getsitepackages().
def getsitepackages():
"""Returns a list containing all global site-packages directories
(and possibly site-python).
For each directory present in the global ``PREFIXES``, this function
will find its `site-packages` subdirectory depending on the system
environment, and will return a list of full paths.
"""
sitepackages = []
seen = set()
for prefix in PREFIXES:
if not prefix or prefix in seen:
continue
seen.add(prefix)
if sys.platform in ('os2emx', 'riscos'):
sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
elif os.sep == '/':
sitepackages.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"site-packages"))
sitepackages.append(os.path.join(prefix, "lib", "site-python"))
else:
sitepackages.append(prefix)
sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
(...)
This function eventually returns a list, and for each element of that list addsitedir function is called - and in that one, you have the logic to get .pth files working.
So long story short - to process .pth files - call site.addistedir in your entry-level script. You might also consider having it in your sitecustomize.py - just be sure your python distribution does not already have one.
来源:https://stackoverflow.com/questions/2794107/should-python-2-6-on-os-x-deal-with-multiple-easy-install-pth-files-in-pythonpa