gpt4 book ai didi

virtualenv 中的 python 模块

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:53 28 4
gpt4 key购买 nike

我在 virtualenv 中使用 python。我有以下模块:

offers/couchdb.py:

from couchdb.client import Server

def get_attributes():
return [i for i in Server()['offers']]

if __name__ == "__main__":
print get_attributes()

当我从文件运行它时,我得到:

$ python offers/couchdb.py
Traceback (most recent call last):
File "offers/couchdb.py", line 1, in <module>
from couchdb.client import Server
File "/Users/bartekkrupa/D/projects/commercial/echatka/backend/echatka/offers/couchdb.py", line 1, in <module>
from couchdb.client import Server
ImportError: No module named client

但是当我将它粘贴到解释器中时......它起作用了:

$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from couchdb.client import Server
>>>
>>> def get_attributes():
... return [i for i in Server()['offers']]
...
>>> if __name__ == "__main__":
... print get_attributes()
...

从文件运行该模块的 python 不加载 couchdb 模块,但在 REPL 中运行会加载 couchdb 模块,这可能是什么原因?

最佳答案

您偶然发现了一个错误特征:相对导入。当您说 from couchdb.client... 时,Python 首先在 offers. 下查找名为 couchdb 的模块。它会找到一个:您正在处理的文件 offers/couchdb.py!

通常的解决方法是禁用此行为,无论如何在 Python 3 中都已消失。将其作为第一行 Python 代码放入您的文件中:

from __future__ import absolute_import

然后 Python 将假定您要从名为 couchdb 的顶级模块导入(您这样做),而不是当前模块的同级模块。

不幸的是,在这种情况下,您直接运行该文件,Python 仍会将 offers/ 添加到其搜索路径中。当运行一个旨在成为模块的文件时,您可以使用 -m 运行它:

python -m offers.couchdb

现在它应该可以工作了。

(当然,您可以不将文件命名为 couchdb.py。但我发现以模块与之交互或包装的对象命名非常有用。)

关于virtualenv 中的 python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14366977/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com