Created
June 7, 2017 11:57
-
-
Save twheys/fc4d2e389a0a31eca53fc4846af5df2c to your computer and use it in GitHub Desktop.
Small generator function that recursively scans a directory for all python modules.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def scan_for_modules(path): | |
""" | |
Generator function which scans a directory for all python modules and returns them successively. | |
""" | |
modules = [] | |
for finder, pkgname, is_module in pkgutil.iter_modules([path]): | |
if pkgname in ['setup']: | |
continue | |
mod = importlib.import_module(pkgname) | |
if not hasattr(mod, '__path__'): | |
continue | |
yield mod | |
modules.append(mod) | |
while modules: | |
mod = modules.pop() | |
for finder, pkgname, is_module in pkgutil.iter_modules(mod.__path__): | |
child_mod = importlib.import_module('%s.%s' % (mod.__name__, pkgname)) | |
yield child_mod | |
if is_module and 'test' != pkgname: | |
modules.append(child_mod) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment