我有一个目录结构如下的项目:
当我尝试使用命令行运行时,如下:
我收到了这个错误。
.
├── 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
来安装依赖和创建虚拟环境。
logger
,你需要显式地导入它;最好的方法是使用from helpers import logger
然后logger.info(...)
。然而,你也应该考虑不做任何操作,而是使用标准库中的logging
模块。 - Daniel Roseman