The ModuleFinder class in 'modulefinder' module can determine set of modules imported by a certain script. This module has a command line interface as well as programmatic interface.
For demonstration of functionality, use following script
#modfinder.py import hello try: import trianglebrowser import nomodule,mymodule except ImportError: pass
Command line interface
Following command displays list of modules located as well as not found.
E:\python37>python -m modulefinder modfinder.py
Output
Name File ---- ---- m __main__ modfinder.py m hello hello.py m math m trianglebrowser trianglebrowser.py Missing modules: ? mymodule imported from __main__ ? nomodule imported from __main__
Programmatic interface
ModuleFinder class in this module provides run_script() and report() methods to determine the set of modules imported by a script.
report()
This method prints a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing.
run_script()
This method analyzes the contents of the given file, which must contain Python code.
modules
This is a dictionary mapping module names to modules.
badmodules
This is a list of modules that could not be loaded.
Example
import modulefinder modfind=modulefinder.ModuleFinder() modfind.run_script('modfinder.py') print ('Modules loaded:') for k,v in modfind.modules.items(): print (k,v) print ('not found:') for i in modfind.badmodules.keys(): print (i)
Output
Modules loaded: __main__ Module('__main__', 'modfinder.py') hello Module('hello', 'E:/python37\\hello.py') trianglebrowser Module('trianglebrowser', 'E:/python37\\trianglebrowser.py') math Module('math') not found: nomodule mymodule