2

What I'm trying to do is get a list of module objects that represent the imports within a specific module, e.g. via inspection/reflection. I can get the global list of imports but this doesn't tell me which module is using which other modules.

To be clear, I'm talking about modules in Python, not packages as installed by PIP. I'm looking for code entirely in Python 2.7 to take a module reference (say sys.modules['foo']) and return a list of that module's imports as either name, path, or another module object. (All I actually want right now is the path.)

import sys
for module_name in sys.modules:
   print "Modules imported by %s are: ..." % (module_name,)

How would you complete the above snippet to actually list the imports?

Neil C. Obremski
  • 18,696
  • 24
  • 83
  • 112

1 Answers1

2

You can use the modulefinder package from the standard library.

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('my_script.py')

for name, mod in finder.modules.iteritems():
    print(name)
Brobin
  • 3,241
  • 2
  • 19
  • 35