Is there a standard way to list names of Python modules in a package?
Is there a standard way to list names of Python modules in a package?
Using python2.3 and above, you could also use the pkgutil
module:
>>> import pkgutil
>>> [name for _, name, _ in pkgutil.iter_modules([testpkg])]
[modulea, moduleb]
EDIT: Note that the parameter for pkgutil.iter_modules
is not a list of modules, but a list of paths, so you might want to do something like this:
>>> import os.path, pkgutil
>>> import testpkg
>>> pkgpath = os.path.dirname(testpkg.__file__)
>>> print([name for _, name, _ in pkgutil.iter_modules([pkgpath])])
import module
help(module)
Is there a standard way to list names of Python modules in a package?
Maybe this will do what youre looking for?
import imp
import os
MODULE_EXTENSIONS = (.py, .pyc, .pyo)
def package_contents(package_name):
file, pathname, description = imp.find_module(package_name)
if file:
raise ImportError(Not a package: %r, package_name)
# Use a set because some may be both source and compiled.
return set([os.path.splitext(module)[0]
for module in os.listdir(pathname)
if module.endswith(MODULE_EXTENSIONS)])