背景
我对__file__属性如何从docs (scroll down to 'modules')和各种网站上工作做了一些研究。在
据我所知,所有python模块都应该有一个__file__属性,只要它是从文件加载的。在
问题
我正在使用安装第三方python模块opencafe(env)$ pip install opencafe
我正在使用这个测试框架。在
当我从CLI运行test命令时,会出现此问题。当这个命令运行时,它会触发这个文件:env/lib/python2.7/site-packages/cafe/configurator/managers.py。在
在那个文件里有
^{pr2}$
后来呢_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 "", line 1, in
AttributeError: 'module' object has no attribute '__file__'
我的想法
我自然倾向于认为这是opencafe本身的问题,因为我只安装框架并从CLI运行测试命令。在
但是,我想知道在虚拟环境中的安装是否有问题,或者可能是PYTHONPATH。在
这些文档清楚地指出,“静态链接到解释器的C模块不存在__file__属性”。这个模块是本地安装的python模块。它不像sys模块那样链接到解释器。在
[编辑]
下面是关于命名空间包的一些更好的信息。在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或更早版本。恢复为我消除了这个错误消息。在
当它与此版本一起安装时,会在virtualenv的包中创建一个__init__.pyc文件。这个字节编译是__file__获取其信息的方式。在