Python 父文件夹子文件夹中的相对导入模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14057464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:18:50  来源:igfitidea点击:

Relative importing modules from parent folder subfolder

pythonimportmodulepython-2.7

提问by Hooked

Given a directory structure like this

给定这样的目录结构

/main/
/main/common/foo.py
/main/A/
/main/A/src/
/main/A/src/bar.py

How can I use Python's relative importsto import foofrom bar? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single importin Python 2.7?

如何使用 Python 的相对导入来导入foofrom bar?我通过将它添加到路径中得到了一个可行的解决方案,但这很难看。有没有办法import在 Python 2.7 中简单地处理单个?

This is a more complex version of this question:

这是这个问题的更复杂版本:

Importing modules from parent folder

从父文件夹导入模块

采纳答案by Claudiu

The correct relative import would be this:

正确的相对导入是这样的:

from ...common import foo

However, relative imports are only meant to work within one package. If mainis a package, then you can use relative imports here. If mainis not a package, you cannot.

但是,相对导入仅适用于一个包。如果main是一个包,那么你可以在这里使用相对导入。如果main不是包,则不能。

Thus, if you're running a script in /main/and doing something like import A.src.bar, then that relative import will fail with "Attempted relative import beyond toplevel package". This is because the relative import is trying to import something outside of the toplevel package A.

因此,如果您正在运行一个脚本/main/并执行类似的操作import A.src.bar,那么该相对导入将失败,并显示“尝试在顶级包之外进行相对导入”。这是因为相对导入试图导入顶级包之外的内容A

However, if you're running a script in /and doing something like import main.A.src.bar, then that relative import will succeed because mainis now a package. In that case, the following two would be equivalent:

但是,如果您正在运行脚本/并执行类似的操作import main.A.src.bar,那么相对导入将成功,因为main现在是一个包。在这种情况下,以下两个将是等效的:

from ...common import foo
from main.common import foo

To answer your comment: the meaning of the .doesn't change depending on where the script was run from, it changes depending on what the package structure is.

回答您的评论: 的含义.不会根据运行脚本的位置而改变,它会根据包结构而改变。