問題描述
有沒有辦法在不修改現(xiàn)有腳本的情況下告訴 Python 其他 site-packages
位置?
在我的 CentOS 5.5 服務器上,我有一個安裝在 /opt/python2.7.2
中的 Python 2.7 安裝,并且 中有一個
.site-packages
文件夾/opt/python2.7.2/lib/python2.7/site-packages
這樣做的原因是我不想干擾 5.5 發(fā)行版附帶的現(xiàn)有 Python 2.4 安裝.
然而,第三方 Python 應用程序還在 /usr/local/lib/python2.7/site-packages
添加了一個 site-packages
文件夾,并將其自身安裝在那個位置.
這部分是我的錯,因為我沒有在安裝之前調(diào)整應用程序的 Makefile
中的 PREFIX
,但是我現(xiàn)在無能為力.
我知道我可以做到:
導入系統(tǒng);sys.path.insert(0, "/usr/local/lib/python2.7/site-packages")
但是,這將涉及我跟蹤每個腳本并添加上述內(nèi)容,如果將來有更新,這并不理想.
為了解決這個問題,我在 /opt/python2.7.2/lib/python2.7/site-packages
中創(chuàng)建了一個指向此第三方應用程序位置的符號鏈接:
這似乎工作正常,但我想知道是否有更好的方法?
您可以使用 Site-具體配置鉤子.
<塊引用>"路徑配置文件是一個文件名,格式為name.pth
,存在于上述四個目錄之一中;其內(nèi)容是要添加的附加項(每行一個)到 sys.path
."
在您的情況下,您應該能夠通過簡單地放入包含要包含的目錄路徑的 .pth
文件來實現(xiàn)您想要的:
[root@home]$ echo "/usr/local/lib/python2.7/site-packages/" >/opt/python2.7.2/lib/python2.7/site-packages/usrlocal.pth
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?
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 tosys.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
這篇關于配置 Python 以使用站點包的其他位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!