Last active
May 24, 2024 20:54
-
-
Save mikecharles/93b323bf045fbf43b157b917bab7987a to your computer and use it in GitHub Desktop.
Python script to list all submodules of a given Python package
This file contains 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
#!/usr/bin/env python | |
import os, sys | |
import pkgutil | |
def list_submodules(list_name, package_name): | |
for loader, module_name, is_pkg in pkgutil.walk_packages(package_name.__path__, package_name.__name__+'.'): | |
list_name.append(module_name) | |
module_name = __import__(module_name, fromlist='dummylist') | |
if is_pkg: | |
list_submodules(list_name, module_name) | |
if len(sys.argv) != 2: | |
print('Usage: {} [PACKAGE-NAME]'.format(os.path.basename(__file__))) | |
sys.exit(1) | |
else: | |
package_name = sys.argv[1] | |
try: | |
package = __import__(package_name) | |
except ImportError: | |
print('Package {} not found...'.format(package_name)) | |
sys.exit(1) | |
all_modules = [] | |
list_submodules(all_modules, package) | |
print(all_modules) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code seems technically correct. And thank you for clarifying the commands by using
import os, sys
instead offrom os import *
andfrom sys import *
to avoid system and other module conflicts.