python:列出包中的模块 [英] python: list modules within the package
问题描述
我有一个包含几个模块的包,每个模块都有一个类(或几个类)。我需要获取包中所有模块的列表。在python中是否有这个API?
I have a package with a few modules, each module has a class (or a few classes) defined within it. I need to get the list of all modules within the package. Is there an API for this in python?
这是文件结构:
\pkg\
\pkg\__init__.py
\pkg\module1.py -> defines Class1
\pkg\module2.py -> defines Class2
\pkg\module3.py -> defines Class3 and Class31
我需要获取列表 pkg 中的模块,然后导入这些模块中定义的所有类
from within module1 I need to get the list of modules within pkg, and then import all the classes defined in these modules
更新1:
好了,在考虑了答案之后下面的评论我认为,这并不容易实现我的需要。为了使我在下面提出的代码有效,所有模块都应该事先明确导入。
Update 1: Ok, after considering the answers and comments below I figured, that it's not that's easy to achieve my need. In order to have the code I proposed below working, all the modules should be explicitly imported beforehand.
所以现在新概念:
如何获取列表包中的模块没有加载模块?使用python API,即 - 没有列出包文件夹中的所有文件?
So now the new concept: How to get the list of modules within a package without loading the modules? Using python API, i.e. - without listing all the files in the package folder?
谢谢
ak
Thanks ak
推荐答案
好吧,这实际上非常简单:
ok, this was actually pretty straightforward:
import pkg
sub_modules = (
pkg.__dict__.get(a) for a in dir(pkg)
if isinstance(
pkg.__dict__.get(a), types.ModuleType
)
)
for m in sub_modules:
for c in (
m.__dict__.get(a) for a in dir(m)
if isinstance(m.__dict__.get(a), type(Base))
):
""" c is what I needed """
这篇关于python:列出包中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!