Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从importlib模块导入子模块_Python_Python Import_Python Importlib - Fatal编程技术网

Python:从importlib模块导入子模块

Python:从importlib模块导入子模块,python,python-import,python-importlib,Python,Python Import,Python Importlib,我有这样一个目录: parent.py ------+ child1.py---+ child2.py---+ ... etc 我可以像这样导入父模块: importlib.import\u模块(“父项”) 那么,既然我已经有了父模块,那么获取子模块的最佳方法是什么呢?我尝试了parent.child1,importlib.import\u模块(“child1”,parent),parent.import\u模块(“child1”),等等,但都没有用 有什么建议吗 谢谢

我有这样一个目录:

parent.py ------+
    child1.py---+
    child2.py---+
    ... etc
我可以像这样导入父模块:

importlib.import\u模块(“父项”)

那么,既然我已经有了父模块,那么获取子模块的最佳方法是什么呢?我尝试了
parent.child1
importlib.import\u模块(“child1”,parent)
parent.import\u模块(“child1”)
,等等,但都没有用

有什么建议吗


谢谢

您可以尝试以以下方式组织文件:

parent (directory)-+
    __init__.py ---+
    child1.py   ---+
    child2.py   ---+
init.py中,您可以从子*文件导入,并且可以从父模块外部导入

示例
\uuuu init\uuuu.py
。它也可以是空的,但必须存在

from child1 import foo
from child2 import bar
从外部使用:

from parent import foo
or
from parent.child1 import foo

这并不能直接回答你的问题。但是,在以上述方式重新组织文件后,请尝试再次使用importlib。

您可以使用可选参数包:

importlib.import_module("child1", package="parent")
文档参考:

可能重复