系统中安装了Python 2.6。
现在,我想使用Python 2.7中引入的模块。因为我没有root特权,所以在主目录($ HOME / local /)下构建并安装了2.7。
我将以下内容添加到$ HOME / .bashrc中:
export PATH=$HOME/local/bin:$PATH export PYTHONPATH=$HOME/local/lib/python2.7:$PYTHONPATH
现在,我遇到了两个我想寻求解决方法的问题。
新安装的Python 2.7在系统的库路径(/usr/lib/python2.6/site-packages/)中找不到2.6模块。
我应该手动将其添加到PYTHONPATH吗?有更好的解决方案吗?
Python 2.6在启动时抱怨:
'import site' failed; use -v for traceback
我想它正在尝试加载2.7个模块(在$ HOME / local / lib / python2.7中)。调用Python 2.6时是否只能加载2.6模块?
谢谢。
简而言之:不要这样做。将该路径称为“ / usr / lib / python * 2.6 * / site-packages /”的原因有很多。
原因之一是,通常在此目录中存储“已编译”的python文件(.pyc)。python 2.6和python 2.7 .pyc文件不兼容:
$ python2.7 /usr/lib/python2.6/sitecustomize.pyc RuntimeError: Bad magic number in .pyc file
python会跳过它无法理解的pyc文件,但是您至少会失去预编译文件的好处。
另一个原因是,事情可能会混淆:
$ strace -f python2.7 /usr/lib/python2.6/sitecustomize.py ... stat("/etc/python2.6", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat("/etc/python2.6", {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 stat("/etc/python2.6/apport_python_hook", 0x7fffa15601f0) = -1 ENOENT (No such file or directory) open("/etc/python2.6/apport_python_hook.so", O_RDONLY) = -1 ENOENT (No such file or directory) open("/etc/python2.6/apport_python_hookmodule.so", O_RDONLY) = -1 ENOENT (No such file or directory) open("/etc/python2.6/apport_python_hook.py", O_RDONLY) = -1 ENOENT (No such file or directory) open("/etc/python2.6/apport_python_hook.pyc", O_RDONLY) = -1 ENOENT (No such file or directory) stat("/usr/lib/python2.7/apport_python_hook", 0x7fffa15601f0) = -1 ENOENT (No such file or directory) open("/usr/lib/python2.7/apport_python_hook.so", O_RDONLY) = -1 ENOENT (No such file or directory) open("/usr/lib/python2.7/apport_python_hookmodule.so", O_RDONLY) = -1 ENOENT (No such file or directory) open("/usr/lib/python2.7/apport_python_hook.py", O_RDONLY) = -1 ENOENT (No such file or directory) open("/usr/lib/python2.7/apport_python_hook.pyc", O_RDONLY) = -1 ENOENT (No such file or directory) stat("/usr/lib/python2.7/plat-linux2/apport_python_hook", 0x7fffa15601f0) = -1 ENOENT (No such file or directory) ...
在您的情况下,我会在python2.7目录中安装python 2.7所需的模块。
您可能需要看一下手册页中描述PYTHONHOME的部分:
PYTHONHOME:更改标准Python库的位置。默认情况下,在$ {prefix} / lib / python [version]和$ {exec_prefix} / lib / python [version]中搜索这些库,其中$ {prefix}和$ {exec_prefix}是与安装有关的目录,默认情况下到/ usr / local
您可以将python 2.7特定文件/模块存储在本地安装中的相应目录中。仅当您运行特定版本的python时,才会选择这些文件/模块。在这种情况下,您不得设置PYTHONPATH(或PYTHONHOME)。
注意:这正是Debian(可能还有其他发行版)管理同时安装的不同python版本的方式。
[编辑:在收到niboshi的评论后,添加了第1节。]