列出作为 python 包一部分的所有模块?

问题描述

有没有一种简单的方法可以找到所有作为 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

相关文章