如何从兄弟目录中的python包导入?

时间:2017-09-27 16:01:07

标签: python python-3.x

我是python的新手,我在使用包和导入时遇到了一些问题。

我的结构如下:

src/
    base/
        packcore/
            __init__.py
            utils/
                __init__.py
                util_1.py
                util_2.py
            helpers/
                __init__.py
                helper_1.py
                helper_2.py
    some_script.py
    app.py

packcore是使用pip安装并放入--target=base的外部包。

helpers中的部分packcore使用部分utils

来自app.py我希望能够导入helper / util

但是当我使用from base.packcore.utils import some_util时,我收到一条错误消息,指出packcore

内没有名为helper/util的模块

如果我from packcore.utils import some_util我收到错误,则没有名为packcore的模块from the app.py`

帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

如果您向__init__.py添加base/,则可以将其作为要导入的Python包。您还需要使父包成为一个包(当前称为src),因此它实际上是一个兄弟模块,而不是许多独立的模块。

从那里,你可以从主包中进行绝对导入:

from src.base.packcore.helpers import helper_1

或亲戚(假设您在some_script.pyapp.py):

from .base.packcore.helpers import helper_1