【发布时间】:2018-05-28 08:07:12
【问题描述】:
我有一个目录结构如下的项目
.
├── Pipfile
├── Pipfile.lock
├── module
│ ├── __init__.py
│ ├── helpers
│ │ ├── __init__.py
│ │ ├── __pycache__
│ │ │ └── __init__.cpython-36.pyc
│ │ ├── dynamo.py
│ │ └── logger.py
│ └── test.py
相关代码
logger.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来安装deps并创建虚拟环境。
【问题讨论】:
-
这不是 Python 包导入的工作方式。如果要使用
logger,需要显式导入;最好的方法是使用from helpers import logger,然后使用logger.info(...)。但是,您也应该考虑不这样做,而是使用 stdlib 中的logging模块。
标签: python python-3.x module python-module pipenv