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?

3
  • 1
    Check out pipreqs. Commented Jul 1, 2015 at 15:29
  • @Brobin: I must have been unclear, I mean Python modules not PIP packages. Commented Jul 1, 2015 at 16:13
  • Gotcha. Perhaps modulefinder is what you are looking for. Commented Jul 1, 2015 at 16:20

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.