Python 相对导入脚本向上两级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36826839/
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-19 18:24:17  来源:igfitidea点击:

Python relative-import script two levels up

pythonpython-3.xpython-importdirectory-structurerelative-import

提问by Luke Taylor

I've been struggling with imports in my package for the last hour.

在过去的一个小时里,我一直在为我的包中的导入而苦苦挣扎。

I've got a directory structure like so:

我有一个这样的目录结构:

main_package
 |
 | __init__.py
 | folder_1
 |  | __init__.py
 |  | folder_2
 |  |  | __init__.py
 |  |  | script_a.py
 |  |  | script_b.py
 |
 | folder_3
 |  | __init__.py
 |  | script_c.py

I want to access code in script_b.pyas well as code from script_c.pyfrom script_a.py. How can I do this?

我想在访问代码script_b.py从以及代码script_c.pyscript_a.py。我怎样才能做到这一点?

If I put a simple import script_binside script_a.py, when I run

如果我import script_b在里面放一个简单的script_a.py,当我跑

from main_package.folder_1.folder_2 import script_b

I am met with an

我遇到了一个

ImportError: no module named "script_b"

For accessing script_c.py, I have no clue. I wasn't able to find any information about accessing files two levels up, but I know I can import files one level up with

对于访问script_c.py,我不知道。我无法找到有关访问上两级文件的任何信息,但我知道我可以导入上一级文件

from .. import some_module

How can I access both these files from script_a.py?

我怎样才能访问这两个文件script_a.py

回答by tobspr

To access script_c and script_b from script_a, you would use:

要从 script_a 访问 script_c 和 script_b,您可以使用:

from ...folder_3 import script_c
from . import script_b

Or if you use python3, you can import script_b from script_a by just using:

或者,如果您使用 python3,则只需使用以下命令即可从 script_a 导入 script_b:

import script_b

However, you should probably use absolute imports:

但是,您可能应该使用绝对导入:

from mypackage.folder_3 import script_c
from mypackage.folder1.folder2 import script_b

Also see: Absolute vs Relative imports

另请参阅:绝对与相对导入