【发布时间】:2018-02-23 15:10:21
【问题描述】:
既然关于相对进口的问题太多了,我会尽量简短和甜美。是的,我读过“Relative imports for the billionth time”。
我有一个这样的项目结构:
.
├── Makefile
└── src
├── __init__.py
├── model
│ └── train_model.py
└── preprocessing
└── process.py
例如,我希望能够调用make preprocessing或make train,然后运行process.py或train_model.py与
## Make train
train:
python3 src/model/train_model.py
例如模块将始终来自 Makefile 所在的顶级项目文件夹。
现在,我的问题是我可能在不同的子模块之间存在依赖关系,例如train_model.py 和process.py。具体来说,如果我尝试使用from src.preprocessing import process 在train_model 中导入process,我会收到错误ImportError: No module named 'src'。同样,我尝试了from ...preprocessing import process,这给了我另一个错误:SystemError: Parent module '' not loaded, cannot perform relative import。
我在train_model.py 的末尾使用了if __name__ == '__main__':,但我似乎无法弄清楚python 是如何使用__name__ 来查找不同的模块的,如果这个f**** 在过程。
【问题讨论】:
标签: python python-3.x python-import relative-import