关于PYTHONPATH的Python 2.x多个版本问题

nib*_*shi 5 python python-2.x pythonpath

系统中安装了Python 2.6.

现在我想使用Python 2.7中引入的模块.因为我没有root权限,所以我在我的主目录下构建并安装了2.7($ HOME/local /)

我在$ HOME/.bashrc中添加了以下内容:

export PATH=$HOME/local/bin:$PATH
export PYTHONPATH=$HOME/local/lib/python2.7:$PYTHONPATH
Run Code Online (Sandbox Code Playgroud)

现在我遇到了我想要解决的两个问题.

1.调用Python 2.7

新安装的Python 2.7在系统的库路径(/usr/lib/python2.6/site-packages/)中找不到2.6模块.

我应该手动将它添加到PYTHONPATH吗?有没有更好的解决方案?

2.调用Python 2.6

Python 2.6在启动时抱怨:

'import site' failed; use -v for traceback
Run Code Online (Sandbox Code Playgroud)

我猜它正在尝试加载2.7个模块(在$ HOME/local/lib/python2.7中).调用Python 2.6时是否可以仅加载2.6个模块?

谢谢.

And*_*ath 4

1)调用python 2.7

简而言之:不要这样做。该路径被称为“/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
Run Code Online (Sandbox Code Playgroud)

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)
...
Run Code Online (Sandbox Code Playgroud)

在你的情况下,我会在 python2.7 目录中安装 python 2.7 所需的模块。

2)调用python 2.6

您可能想查看手册页中描述 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 节。]