虚拟环境下的Python 2.7: `site.py`损坏

4 投票
3 回答
1689 浏览
提问于 2025-04-16 18:04

当我用Python 2.7创建一个新的虚拟环境时,我无法使用 site.getsitepackages()

$ virtualenv testenv -p python2.7 --no-site-packages
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in testenv/bin/python2.7
Also creating executable in testenv/bin/python
Installing setuptools............done.
Installing pip...............done.
$ cd testenv/
$ source bin/activate
(testenv)$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> site.getsitepackages()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

AttributeError: 'module' object has no attribute 'getsitepackages'

看起来 site.py 里没有应该在Python 2.7中出现的新功能。

有什么建议吗?

补充:即使我不使用 --no-site-packages,问题依然存在:

$ virtualenv testenv -p python2.7
Running virtualenv with interpreter /usr/bin/python2.7
New python executable in testenv/bin/python2.7
Also creating executable in testenv/bin/python
Installing setuptools............done.
Installing pip...............done.
$ cd testenv/
$ source bin/activate
(testenv)$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> site.getsitepackages()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getsitepackages'

3 个回答

0

这可能不是导致你问题的原因,但在我调试了4个小时后,这对我有帮助(而且我是在一年后才来回答这个问题的 :)。

virtualenv/bin/python 这个文件必须是可以执行的。

所以……

chmod +x virtualenv/bin/python

在这里有效。

0

你正在使用 --no-site-packages 这个选项,这样会导致新创建的环境不继承已有的库文件。

1

这是一个在后来的virtualenv版本中修复的错误。我查了一下相关记录,但没找到具体的那个。

撰写回答