Q:

How to list imports within a Python module?

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?

A:

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)

