Python Modulefinder Module
The modulefinder module provides a ModuleFinder class that can be used to determine the set of modules imported by a script. modulefinder.py can also be run as a script, giving the filename of a Python script as its argument, after which a report of the imported modules will be printed.
Importing the Module
import modulefinder
Basic Usage
To use modulefinder programmatically, you instantiate the ModuleFinder class and run a script against it.
from modulefinder import ModuleFinder
import os
# Create a dummy script for demonstration
script_name = "myscript.py"
with open(script_name, "w") as f:
f.write("import os\nimport sys\nimport math\n")
finder = ModuleFinder()
finder.run_script(script_name)
print('Loaded modules:')
for name, mod in finder.modules.items():
print(f"{name}: {mod}")
print('-'*20)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))
# Clean up
os.remove(script_name)
The ModuleFinder Class
run_script(pathname)
Analyzes the contents of the file at pathname.
Attributes
modules: A dictionary mapping module names to modules.badmodules: A dictionary mapping names of modules that could not be found to the names of the modules that imported them.
Command Line Usage
You can also use modulefinder from the command line.
python -m modulefinder myscript.py