列出属于 python 包的所有模块? [英] List all the modules that are part of a python package?
问题描述
有没有一种直接的方法可以找到属于 python 包的所有模块?我找到了这个旧讨论,其中并不是真正的决定性的,但在我推出基于 os.listdir() 的我自己的解决方案之前,我很想有一个明确的答案.
Is there a straightforward way to find all the modules that are part of a python package? I've found this old discussion, which is not really conclusive, but I'd love to have a definite answer before I roll out my own solution based on os.listdir().
推荐答案
是的,你想要基于 pkgutil
或类似的东西——这样你就可以一视同仁地对待所有包,无论它们是否在鸡蛋中或 zips 左右(其中 os.listdir 无济于事).
Yes, you want something based on pkgutil
or similar -- this way you can treat all packages alike regardless if they are in eggs or zips or so (where os.listdir won't help).
import pkgutil
# this is the package we are inspecting -- for example 'email' from stdlib
import email
package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
print "Found submodule %s (is a package: %s)" % (modname, ispkg)
如何导入它们?您可以照常使用 __import__
:
How to import them too? You can just use __import__
as normal:
import pkgutil
# this is the package we are inspecting -- for example 'email' from stdlib
import email
package = email
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
print "Found submodule %s (is a package: %s)" % (modname, ispkg)
module = __import__(modname, fromlist="dummy")
print "Imported", module
这篇关于列出属于 python 包的所有模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!