python - 导入的第三方模块没有 __file__ 属性

标签 python python-2.7

背景

我研究了 docs (scroll down to 'modules') 中的 __file__ 属性是如何工作的, 以及各种网站。

据我所知,所有 python 模块都应该有一个 __file__ 属性,只要它是从文件加载的。

问题

我正在使用

安装第三方 python 模块 opencafe
(env)$ pip install opencafe

我正在使用这个测试框架。

当我从 CLI 运行测试命令时出现问题。运行该命令时,它会触发此文件:env/lib/python2.7/site-packages/cafe/configurator/managers.py

在该文件中有

import cafe

以后

_PLUGIN_DIR = os.path.join(os.path.dirname(cafe.__file__), 'plugins')

运行此文件时,出现此错误:

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

在这种情况下会出现同样的错误:

(env) $ pip install opencafe
Collecting opencafe
  Using cached opencafe-0.3.1-py2.py3-none-any.whl
Installing collected packages: opencafe
Successfully installed opencafe-0.3.1
(env) $ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
>>> import cafe
>>> cafe.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'

我的想法

我的自然倾向是相信这是 opencafe 本身的问题,因为我只是安装框架并从 CLI 运行测试命令。

但是,我想知道是否安装到虚拟环境或 PYTHONPATH 中存在问题。

文档清楚地说“对于静态链接到解释器的 C 模块,__file__ 属性不存在”。该模块是本地安装的python模块。它不像 sys 模块那样链接到解释器。

[编辑]

这里有一些关于命名空间包的更多有用信息。

http://chimera.labs.oreilly.com/books/1230000000393/ch10.html#_discussion_172

The main way that you can tell if a package is serving as a namespace package is to check its __file__ attribute. If it’s missing altogether, the package is a namespace.

最终更新

事实证明,opencafe 不适用于最新版本的 virtualenv。它仅适用于版本 15.0.1 或更早版本。恢复为我摆脱了这个错误消息。

当它安装这个版本时,一个 __init__.pyc 文件被创建在 virtualenv 的包中。此字节编译是 __file__ 获取其信息的方式。

最佳答案

那是因为 opencafe 不是一个普通的 python 模块。当你打开他们的主模块时你可以很容易地看到这个 __init__ .

declare_namespace 显式地创建了一个namespace 包。有关此的更多信息,您可以访问 PEP-382 .

关于python - 导入的第三方模块没有 __file__ 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41384526/

相关文章:

python - 如何将字符串彼此放在一起并为其分配一个数字?

python - 如何使用groupby方法组合多个(使用切片?)列或行?

python - 如何按用户 ID 按小时迭代选择平均值?

python - 使用插值和 alpha 将 imshow 保存为 pdf 时出现 Matplotlib 问题

python - 在 3d numpy 数组中查找 k 个最近邻

python - 如何在使用新语言功能的程序中检查 Python 版本?

python-2.7 - 在python中使用pandas连接后如何为每个数据帧放置标题

python - 使用 Python 对以元组为元素的列表进行排序

python - 打印在 __getattr__ 中不起作用

python-2.7 - Python,从运行命令获取状态