简体   繁体   English

Python 从父目录相对导入

[英]Python relative imports from parent directory

Here is the file structure I have:这是我的文件结构:

app/
    main.py
    folder/
        a.py
        b.py

In the file a.py i have import b , and in main.py , i have import folder.a .在文件a.py中,我有import b ,在main.py中,我有import folder.a

When I run python3 a.py from folder/ , everything works fine.当我从folder/运行python3 a.py时,一切正常。 However when I run python3 main.py from app/ , I get ModuleNotFoundError: No module named b , which is caused by the import in a.py但是,当我从app/运行python3 main.py时,我得到ModuleNotFoundError: No module named b ,这是由a.py中的导入引起的

I have found a way to avoid this, which is to simply put import folder.b in a.py , but this is not very satisfying, as I can no longer lauch a.py from folder/ .我找到了一种避免这种情况的方法,就是简单地将import folder.b放在a.py中,但这不是很令人满意,因为我无法再从folder/启动a.py

What should i do for the import to work from both folder?我应该怎么做才能从两个文件夹导入? Please don't answer my question by saying i should modify my architecture, i've been looking for answers to this question on SO for 2 hours but i haven't found anything convincing.请不要通过说我应该修改我的体系结构来回答我的问题,我一直在 SO 上寻找这个问题的答案 2 小时,但我没有找到任何令人信服的东西。

In a.py try:在 a.py 中尝试:

from folder import b

or:要么:

from folder.anotherfolder import b

or in main.py:或者在 main.py 中:

from folder import a, b

or:要么:

from folder.anotherfolder import a, b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从父目录的相对导入 - Relative imports from parent directory 在具有从另一个目录的相对导入的模块上运行Python - Running Python on a module with relative imports from another directory python返回相对父目录 - python return relative parent directory 为什么 Colab 找不到相对导入的父目录? - Why does Colab not find the parent directory for relative imports? 如何在不使用文件中的相对导入的情况下从不同目录中的 Python 脚本执行文件(导入其他模块)? - How can I execute a file (that imports other modules) from a Python script in a different directory without using relative imports in the file? 使用 Python 3 从位于另一个目录中的模块导入本地 function 并在 Jupyter Notebook 中进行相对导入 - Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3 Python从上面的目录导入 - Python Imports From The Directory Above 在python中将应用程序与逻辑和相对导入分开 - Separating application from logic and relative imports in python Python 3中的动态导入+相对导入 - Dynamic imports + relative imports in Python 3 在python中将相对导入与多个父级和子级文件夹一起使用 - Using relative imports in python with mutliple parent and children folders
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM