列出所有属于python软件包的模块吗? [英] List all the modules that are part of a python package?

查看:108
本文介绍了列出所有属于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或类似物的东西-通过这种方式,您可以将所有包装都一样对待,而不管它们是鸡蛋还是拉链( 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆