Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

Configuring Python to use additional locations for site-packages

Is there a way to tell Python about additional site-packages locations without modifying existing scripts?

On my CentOS 5.5 server I have a Python 2.7 installation that is installed in /opt/python2.7.2 and there is a site-packages folder at /opt/python2.7.2/lib/python2.7/site-packages.

The reason for this is that I didn't want to disturb the existing Python 2.4 install that shipped with the 5.5 distribution.

However a third party Python application also added a site-packages folder at: /usr/local/lib/python2.7/site-packages and installed itself at that location.

This is partly my fault because I didn't tweak the PREFIX in the application's Makefile before installing, however there's not much I can do about it now.

I know that I can do this:

import sys; sys.path.insert(0, "/usr/local/lib/python2.7/site-packages")

However it would involve me tracking down every script and adding the above which is not ideal should there be updates in the future.

To get around this I created a symbolic link in /opt/python2.7.2/lib/python2.7/site-packages to the location of this third party application:

ln -sf /usr/local/lib/python2.7/site-packages/theapp /opt/python2.7.2/lib/python2.7/site-packages/theapp

This appears to work fine but I'm wondering if there's a better way?

question from:https://stackoverflow.com/questions/7901373/configuring-python-to-use-additional-locations-for-site-packages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Site-specific configuration hook.

"A path configuration file is a file whose name has the form name.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path."

In your case, you should be able to achieve what you want by simply dropping in a .pth file containing the path of the directory to include:

[root@home]$ echo "/usr/local/lib/python2.7/site-packages/" > /opt/python2.7.2/lib/python2.7/site-packages/usrlocal.pth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...