如何导入所有子模块? [英] How to import all submodules?
问题描述
我的目录结构如下:
| main.py
| scripts
|--| __init__.py
| script1.py
| script2.py
| script3.py
从 main.py
,导入模块脚本
。我尝试将 pkgutils.walk_packages
与 __ all __
结合使用,但是使用它,我只能直接导入所有子模块从脚本导入* 使用
? main
。我想把它们都放在脚本
下。导入脚本
的所有子模块的最简洁方法是什么,以便我可以从<$访问 scripts.script1
c $ c> main
From main.py
, the module scripts
is imported. I tried using pkgutils.walk_packages
in combination with __all__
, but using that, I can only import all the submodules directly under main
using from scripts import *
. I would like to get them all under scripts
. What would be the cleanest way to import all the submodules of scripts
so that I could access scripts.script1
from main
?
编辑:对不起,我有点模糊。我想在运行时导入子模块,而不在 __ init __。py
中明确指定它们。我可以使用 pkgutils.walk_packages
来获取子模块名称(除非有人知道更好的方法),但我不确定使用这些名称的最简洁方法(或者可能) walk_packages
的ImpImporters返回?)导入它们。
I am sorry that I was a bit vague. I would like to import the submodules on run-time without specifying them explicitly in __init__.py
. I can use pkgutils.walk_packages
to get the submodule names (unless someone knows of a better way), but I am not sure of the cleanest way to use these names (or maybe the ImpImporters that walk_packages
returns?) to import them.
推荐答案
编辑:这是在运行时以递归方式导入所有内容的一种方法...
Here's one way to recursively import everything at runtime...
它使用exec,因此几乎可以肯定有更好的方法,但它确实如此工作(即使对于任意嵌套的子包,我认为)。
It uses exec, so there's almost certainly a better way, but it does work (even for arbitrarily nested sub-packages, I think).
(顶部的 __ init __。py
的内容包目录)
(Contents of __init__.py
in top package directory)
import pkgutil
__all__ = []
for loader, module_name, is_pkg in pkgutil.walk_packages(__path__):
__all__.append(module_name)
module = loader.find_module(module_name).load_module(module_name)
exec('%s = module' % module_name)
我没有使用 __ import __(__ path __ +如果您没有嵌套的子包,并且想要避免
exec
/ eval
,那么它就是一个这样做的方法。
I'm not using __import__(__path__+'.'+module_name)
here, as it's difficult to properly recursively import packages using it. If you don't have nested sub-packages, and wanted to avoid the exec
/eval
, though, it's one way to do it.
可能有更好的方法,但无论如何这是我能做的最好的。
There's probably a better way, but this is the best I can do, anyway.
原始答案(对于上下文,请忽略。我最初误解了这个问题):
Original Answer (For context, ignore othwerwise. I misunderstood the question initially):
你的脚本是什么/ __ init __。py
看起来像?它应该类似于:
What does your scripts/__init__.py
look like? It should be something like:
import script1
import script2
import script3
__all__ = ['script1', 'script2', 'script3']
你甚至可以不定义 __ all __
,但是如果你定义的东西(pydoc,如果没有别的话)会更干净地工作,即使它只是你导入的列表。
You could even do without defining __all__
, but things (pydoc, if nothing else) will work more cleanly if you define it, even if it's just a list of what you imported.
这篇关于如何导入所有子模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!