Python Pkgutil Module
The pkgutil module provides utilities for the import system, in particular for package support. It is often used to iterate over modules in a package or to read data files included in a package.
Importing the Module
import pkgutil
Iterating Over Modules
You can iterate over all modules available in a given path using pkgutil.iter_modules().
import pkgutil
# Iterate over all top-level modules
for module_info in pkgutil.iter_modules():
print(module_info.name)
To iterate over modules within a specific package, pass the package's __path__.
import pkgutil
import urllib # Example package
print(f"Modules in {urllib.__name__}:")
for loader, name, is_pkg in pkgutil.iter_modules(urllib.__path__):
print(f"Name: {name}, Is Package: {is_pkg}")
Walking Packages
pkgutil.walk_packages() is similar to iter_modules(), but it is recursive. It yields all modules found on the path and in sub-packages.
import pkgutil
import email # Example package with sub-packages
print(f"All modules in {email.__name__}:")
for loader, name, is_pkg in pkgutil.walk_packages(email.__path__, email.__name__ + "."):
print(name)
Reading Data
pkgutil.get_data() allows you to read a resource from a package. It is a wrapper for the loader's get_data method.
import pkgutil
# Read a file named 'templates/template.html' from the 'myapp' package
# data = pkgutil.get_data('myapp', 'templates/template.html')