Python:属性错误,模块x没有属性y。

4
我有一个目录结构如下的项目:
.
├── Pipfile
├── Pipfile.lock
├── module
│   ├── __init__.py
│   ├── helpers
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── dynamo.py
│   │   └── logger.py
│   └── test.py

相关代码

日志记录器.py

import click
import sys
from tabulate import tabulate


def formatter(string, *rest):
    return string.format(*rest)


def info(*rest):
    """Write text in blue color
    """
    click.echo(click.style('☵ ' + formatter(*rest), fg='blue'))

test.py

import helpers

helpers.logger.info('Trying')

当我尝试使用命令行运行时,如下:
python3 module/test.py

我收到了这个错误。
Traceback (most recent call last):
  File "module/test.py", line 4, in <module>
    helpers.logger.info('Trying')
AttributeError: module 'helpers' has no attribute 'logger'

我已经尝试重构代码。将helpers目录放在与module目录同级的位置。但是,它仍然没有起作用,但根据我的阅读,它不应该有问题。我尝试研究了一些关于__init__.py和python模块系统的内容。我读得越多,就越感到困惑。但从我所学到的知识中,我创建了另一个示例项目,其结构如下:

.
└── test
    ├── __init__.py
    ├── helpers
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── quote.cpython-36.pyc
    │   └── quote.py
    ├── index.py
    ├── logger
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-36.pyc
    │   │   └── info.cpython-36.pyc
    │   └── info.py

代码与第一个项目相同。

在这里,当我执行以下操作时,

python3 test/index.py

它按预期工作。两个项目之间唯一的区别是:

在第一个项目中,我使用了 pipenv 来安装依赖和创建虚拟环境。


1
这不是 Python 包导入的工作方式。如果你想使用 logger,你需要显式地导入它;最好的方法是使用 from helpers import logger 然后 logger.info(...)。然而,你也应该考虑不做任何操作,而是使用标准库中的 logging 模块。 - Daniel Roseman
2个回答

8
使用您最初的布局(其中loggershelpers包的子模块),您需要在helpers/__init__.py中显式导入loggers,以将其作为helpers包的属性公开:
# helpers/__init__.py
from . import logger

经过多次在stackoverflow上的搜索,这就是我一直在寻找的答案 - 谢谢! - cgnorthcutt
作为Python的新手,这非常有帮助。 - berimbolo

6

logger 是模块而不是属性,helpers.loggerlogger 解释为属性。实际上,您应该按照以下方式操作:

from helpers import logger

print(logger.info('Trying'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接