List All Modules Provided By A Python Package

The following is an example of how to use the “pkg_resources” module (provided by the setuptools project) to compose a list of all available modules in a Python package.

#! /usr/bin/env python

import sys

try:
    import pkg_resources
except ImportError:
    sys.stderr.write("'pkg_resources' could not be imported: setuptools installation required\n")
    sys.exit(1)

def list_package_modules(package_name):
    """
    Returns list of module names for package `package_name`.
    """
    try:
        contents = pkg_resources.resource_listdir(package_name, "")
    except ImportError:
        return []
    module_names = []
    for entry in contents:
        if pkg_resources.resource_isdir(package_name, entry):
            module_names.extend(list_package_modules(package_name + "." + entry))
        elif not entry.endswith('.pyc'):
            if entry.endswith(".py"):
                entry = entry[:-3]
            module_names.append(package_name + "." + entry)
    return module_names

if __name__ == "__main__":
    m = list_package_modules("dendropy")
    print "\n".join(m)
Share