【问题标题】:Python importing a module from a parallel directoryPython从并行目录导入模块
【发布时间】:2014-08-28 14:40:17
【问题描述】:

我将如何组织我的 python 导入,以便我可以拥有这样的目录。

project
|      \
|      __init__.py
|     
src
|   \
|    __init__.py
|    classes.py
|
test
    \
     __init__.py
     tests.py

然后在/project/test/tests.py里面就可以导入classes.py了

我在 tests.py 中有这样的代码

from .. src.classes import(
    scheduler
    db
)

我得到了

的错误
SystemError: Parent module '' not loaded, cannot perform relative import

有人知道该怎么做吗?

【问题讨论】:

    标签: python import module parent relative-import


    【解决方案1】:

    Python 会将包含您启动的脚本的文件夹添加到 PYTHONPATH,所以如果您运行

    python test/tests.py
    

    只有文件夹 test 被添加到路径中(不是您在其中执行命令的基本目录)。

    改为像这样运行您的测试:

    python -m test.tests
    

    这会将基本目录添加到 python 路径,然后可以通过非相对导入访问类:

    from src.classes import etc
    

    如果你真的想使用相对导入风格,那么你的3个目录需要添加到一个包目录中

    package
    * __init__.py
    * project
    * src
    * test
    

    然后你从包目录上方执行它

    python -m package.test.tests
    

    另见:

    【讨论】:

    • 如果您得到“没有名为 test.tests 的模块”,请确保您的 test/ 目录中有一个 __init__.py
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多