問題描述
有沒有一種簡單的方法可以找到所有作為 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 包一部分的所有模塊?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!