virtualenv中的python模块

我在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.但我发现将模块命名为与它们交互或包装的东西非常有用.)

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...