对来自的困惑。导入模块名称

2024-09-28 21:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

也许我对这个话题不太了解。我可以导入“兄弟姐妹”或“侄子”目录,但不能导入“表亲”目录。我阅读了thisPython文档,并尝试按它们显示的方式进行操作,但仍然无法导入“combian”目录。在我的示例中,我的目录结构如下所示:

"""+
   |__directory_1+
   |             |__directory_1_1+
   |             |               |__test_1_1.py
   |             |
   |             |__directory_1_2+
   |             |               |__test_1_2.py
   |             |
   |             |__test_1.py
   |
   |__directory_2+
   |             |__directory_2_1+
   |             |               |__test_2_1.py
   |             |
   |             |__directory_2_2+
   |             |               |__test_2_2.py
   |             |
   |             |__test_2.py
   |
   |__test.py"""

例如:当我运行测试.py归档并编写以下代码:

^{pr2}$

此代码导入它的同级。在

例如:当我运行测试.py再次归档并编写以下代码:

from directory_1 import test_1
from directory_2 import test_2

此代码导入其侄子,也可以导入其侄子,如下所示:

from directory_1.directory_1_1 import test_1_1
from directory_1.directory_1_2 import test_1_2
#...And can be adaptated to other ''grand nephews''.

但是假设我想导入“表亲”文件。如何导入表亲文件?我运行test_1.py文件。“表弟”是“测试2”。在

import directory_1_1.test_1_1
#It can import the 'nephew'.

from . import test_2
#It can't import the 'cousin'.
#SystemError: Parent module '' not loaded, cannot perform relative import

当我阅读上面给出的Python文档时,在包内引用主题中有一个关于这个示例的示例。并且已经编写了一个如下所示的方法来导入“coming”模块。在

from . import module_name

在我的示例中,目录中没有init.py文件。我怀疑问题是从这里来的。我也在想,在init里有什么我还没学过的东西吗?在

当我在思考为什么仍然出现这样的错误:父模块“”未加载,无法执行相对导入>;我在Python文档中所示的目录中添加了一个空的init.py文件。

我希望我能解释我的问题。当然,作为Python的初学者,我想学习如何使用'from。导入模块“表达式。 谢谢。在


Tags: 模块文件代码from文档pytestimport
2条回答

添加路径的优点系统路径从一个模块导入比从一个模块导入更简单。在

说 Soundpackage有sound、modifysound、AudioEnhancement 等等,它们是包装内的模块。在

import sys
sys.path.append('your_path/foo/bar/soundpackage') 
#your module name
from sound import effects.reverse.py
from modifysound import some_module

Import语句依赖于执行的主脚本,或者更确切地说,执行主脚本的目录将自动添加到sys.path中,Python使用该目录在导入时搜索模块。在

因此,如果您运行test.py脚本,最终导入directory_1.directory_1_1.test_1_1,如果该脚本有import directory_2.directory_2_1.test_1_1则一切正常,但如果其他脚本从其他地方调用它,它将无法找到它。在

因此,在制作相互依赖的模块时,因为您无法知道谁将导入这些模块,所以始终使用相对路径。例如,test_2_2.py可以导入它的test_1_1.py'表亲':from ....directory_1.directory_1_1 import test_1_1(相对名遵循与路径名相似的规则,只是不需要分隔符,所以.是当前路径,..是上一级的路径,...是上两级的路径,依此类推)。在

注意:这些类型的多级相对导入只在包中使用时才起作用,您不能使用它来引用正在运行的脚本(当您知道所有东西从何处运行时,为什么还要这样做呢?)。所有目录都需要有__init__.py,这样Python解释器才能将其视为。在

相关问题 更多 >