导入子模块的子模块上的 ModuleNotFoundError
ModuleNotFoundError on a submodule that imports a submodule
让我们假设我们有以下结构:
outer_module.py|
|subfolder|
|__init__.py
|inner_module.py
|foo.py
在 outer_module.py
中我们有:
from subfolder.inner_module import X
在 inner_module.py
中我们有:
from foo import Y
然后我得到一个ModuleNotFoundError: No module named 'foo'
运行 outer_module.py
。如何在不获取 ModuleNotFoundError 的情况下导入这个导入子模块的子模块?
from foo
从 顶级 模块 foo
导入。您需要明确限定您正在寻找同一包中的模块。
使用.foo
表示您正在从同一个包中导入:
from .foo import Y
你也可以指定一个绝对路径,但是你必须包含包名:
from subfolder.foo import Y
引自import
statement documentation:
When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod
from a module in the pkg
package then you will end up importing pkg.mod
. If you execute from ..subpkg2 import mod
from within pkg.subpkg1
you will import pkg.subpkg2.mod
.
在 inner_module.py
中,使用相对或绝对导入:
from .foo import Y
# or
from subfolder.foo import Y
文档链接:
让我们假设我们有以下结构:
outer_module.py|
|subfolder|
|__init__.py
|inner_module.py
|foo.py
在 outer_module.py
中我们有:
from subfolder.inner_module import X
在 inner_module.py
中我们有:
from foo import Y
然后我得到一个ModuleNotFoundError: No module named 'foo'
运行 outer_module.py
。如何在不获取 ModuleNotFoundError 的情况下导入这个导入子模块的子模块?
from foo
从 顶级 模块 foo
导入。您需要明确限定您正在寻找同一包中的模块。
使用.foo
表示您正在从同一个包中导入:
from .foo import Y
你也可以指定一个绝对路径,但是你必须包含包名:
from subfolder.foo import Y
引自import
statement documentation:
When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute
from . import mod
from a module in thepkg
package then you will end up importingpkg.mod
. If you executefrom ..subpkg2 import mod
from withinpkg.subpkg1
you will importpkg.subpkg2.mod
.
在 inner_module.py
中,使用相对或绝对导入:
from .foo import Y
# or
from subfolder.foo import Y
文档链接: