Python: finding all packages inside a package

Given a package, how can I automatically find all of its subpackages?

+6
python import packages
source share
2 answers

You cannot rely on the introspection of loaded modules because subpackages may not have been loaded. You will need to look at the file system, assuming that the top-level package in question is not an egg, zip file, extension module, or loaded from memory.

def get_subpackages(module): dir = os.path.dirname(module.__file__) def is_package(d): d = os.path.join(dir, d) return os.path.isdir(d) and glob.glob(os.path.join(d, '__init__.py*')) return filter(is_package, os.listdir(dir)) 
+9
source share

Inspired by James Emerton:

 def find_subpackages(module): result=[] for thing in os.listdir(os.path.dirname(module.__file__)): full=os.path.join(os.path.dirname(module.__file__),thing) if os.path.isdir(full): if glob.glob(os.path.join(full, '__init__.py*'))!=[]: result.append(thing) return result 
0
source share

All Articles