python - `__init__.py` 不起作用并导致 ModuleNotFoundError
问题描述
我试图让 python 在不使用的情况下识别包sys.path.append()
__init__.py
这是添加到每个子目录后目录的样子
├── Config
│ ├── __init__.py
│ ├── augmentation_options.py
│ ├── beverly_hills.txt
│ ├── coco.txt
│ ├── set_annotation_conf.py
│ ├── voc_conf.json
│ ├── yolo3.cfg
│ └── yolo4.cfg
├── Data
│ ├── Photos
│ ├── TFRecords
│ ├── XML\ Labels
│ ├── __init__.py
│ └── bh_labels.csv
├── Docs
│ ├── Augmentor.md
│ ├── Evaluator.md
│ ├── Predictor.md
│ ├── Trainer.md
│ └── __init__.py
├── Helpers
│ ├── __init__.py
│ ├── __pycache__
│ │ └── utils.cpython-37.pyc
│ ├── anchors.py
│ ├── annotation_parsers.py
│ ├── augmentor.py
│ ├── dataset_handlers.py
│ ├── scratch
│ │ └── label_coordinates.csv
│ ├── utils.py
│ └── visual_tools.py
├── LICENSE
├── Logs
│ ├── __init__.py
│ └── session.log
├── Main
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-37.pyc
│ │ └── models.cpython-37.pyc
│ ├── detector.py
│ ├── evaluator.py
│ ├── models.py
│ └── trainer.py
├── Models
│ └── __init__.py
├── Output
│ ├── Data
│ ├── Detections
│ ├── Evaluation
│ ├── Plots
│ └── __init__.py
├── README.md
├── Samples
│ ├── __init__.py
│ ├── anchors.png
│ ├── anchors_sample.png
│ ├── aug1.png
│ ├── data.png
│ ├── detections.png
│ ├── eval.png
│ ├── map.png
│ ├── pr.png
│ ├── sample_image.png
│ └── true_false.png
├── __init__.py
└── requirements.txt
当我尝试这个时:
% cd Main
% python3 models.py
models.py
从中导入Helpers.utils
,我得到通常的错误:
emadboctor@MacBook-Pro Main % python3 models.py
Traceback (most recent call last):
File "models.py", line 23, in <module>
from Helpers.utils import get_boxes, timer, default_logger, Mish
ModuleNotFoundError: No module named 'Helpers'
没有什么能真正改变这种行为,除非我这样做:(在 models.py 和每个包含 python 模块的子目录中)
import sys
sys.path.append('..')
据我所知,__init__.py
应该与这些麻烦有关,或者有什么意义__init__.py
?
当然,任何相对导入都会导致以下错误:
在models.py
:
emadboctor@MacBook-Pro Main % python3 models.py
Traceback (most recent call last):
File "models.py", line 23, in <module>
from ..Helpers.utils import get_boxes, timer, default_logger, Mish
ImportError: attempted relative import with no known parent package
emadboctor@MacBook-Pro Main %
解决方案
推荐阅读
- python - 将列值与行切片中的 n 行值进行比较
- regular-language - 你如何解释它?(u∈Σ∗)
- assembly - 将原始二进制文件作为软盘加载到 virtualbox 与从 U 盘加载到真实机器上时的二进制输出之间的差异
- laravel - 当我使用 maatwebsite 通过 csv 输入数据时,如何在 laravel 中重复验证
- javascript - 在其他页面 vue.js 上定义的 js 中执行函数
- php - 网站显示“/的索引”页面而不是主页,存在 index.php
- python - Python 中的 selenium 问题(可能安装 chrome webdriver)
- kubernetes - GitOps (Flex) 通过 HelmRelease 操作符在 Kubernetes 中安装标准 Jenkins Helm 图表
- python - 将 TF2.0 中的 feed_dict 替换为函数中张量的张量输入
- javascript - Firestore 中的更新和删除函数反应原生