微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐