我在virtualenv中使用
python.我有以下模块:
提供/ 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",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.client …说,Python首先在offer下寻找一个模块.这个名字叫couchdb.它找到一个:你正在处理的文件,提供/ couchdb.py!
通常的解决方法是禁用此行为,无论如何,这在Python 3中已经消失.将此作为您文件中的第一行Python代码:
from __future__ import absolute_import
然后Python会假设您要从名为couchdb(您这样做)的顶级模块导入,而不是当前模块的兄弟.
不幸的是,在这种情况下,您正在直接运行该文件,Python仍然会向其搜索路径添加商品/.运行要作为模块的文件时,可以使用-m运行它:
python -m offers.couchdb
现在它应该工作.
(当然,您可以不将文件命名为couchdb.py.但我发现将模块命名为与它们交互或包装的东西非常有用.)