Finding modules used by a Python script (modulefinder)

The ModuleFinder class in Python's modulefinder module can determine the set of modules imported by a script. This module provides both a command line interface and programmatic interface for analyzing module dependencies.

Sample Script for Testing

For demonstration, let's create a test script that imports various modules −

# modfinder.py
import hello
try:
    import trianglebrowser
    import nomodule, mymodule
except ImportError:
    pass

Command Line Interface

Use the module from command line to display modules found and missing −

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

The ModuleFinder class provides methods and attributes for analyzing module dependencies programmatically.

Key Methods and Attributes

  • run_script(filename) − Analyzes the contents of the given Python file
  • report() − Prints a report listing imported modules and their paths
  • modules − Dictionary mapping module names to module objects
  • badmodules − Dictionary of modules that could not be loaded

Example

import modulefinder

# Create ModuleFinder instance
modfind = modulefinder.ModuleFinder()

# Analyze the script
modfind.run_script('modfinder.py')

print('Modules loaded:')
for name, module in modfind.modules.items():
    print(f"{name}: {module}")

print('\nModules not found:')
for module_name in modfind.badmodules.keys():
    print(module_name)

Expected Output

Modules loaded:
__main__: Module('__main__', 'modfinder.py')
hello: Module('hello', 'hello.py')
trianglebrowser: Module('trianglebrowser', 'trianglebrowser.py')
math: Module('math')

Modules not found:
nomodule
mymodule

Using the Report Method

The report() method provides a formatted output similar to the command line interface −

import modulefinder

modfind = modulefinder.ModuleFinder()
modfind.run_script('modfinder.py')

# Print formatted report
modfind.report()

Conclusion

The modulefinder module is useful for dependency analysis and debugging import issues. Use the command line interface for quick analysis or the programmatic interface for automated dependency checking in larger projects.

Updated on: 2026-03-25T05:13:18+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements