python - How to list imported modules?

ID : 20145

viewed : 17

Tags : pythonpython

Top 5 Answer for python - How to list imported modules?

vote vote

94

import sys sys.modules.keys() 

An approximation of getting all imports for the current module only would be to inspect globals() for modules:

import types def imports():     for name, val in globals().items():         if isinstance(val, types.ModuleType):             yield val.__name__ 

This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import module as alias; yield name instead if you want the alias.

vote vote

90

Find the intersection of sys.modules with globals:

import sys modulenames = set(sys.modules) & set(globals()) allmodules = [sys.modules[name] for name in modulenames] 
vote vote

80

If you want to do this from outside the script:

Python 2

from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script("myscript.py") for name, mod in finder.modules.iteritems():     print name 

Python 3

from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script("myscript.py") for name, mod in finder.modules.items():     print(name) 

This will print all modules loaded by myscript.py.

vote vote

67

print [key for key in locals().keys()        if isinstance(locals()[key], type(sys)) and not key.startswith('__')] 
vote vote

51

let say you've imported math and re:

>>import math,re 

now to see the same use

>>print(dir()) 

If you run it before the import and after the import, one can see the difference.

Top 3 video Explaining python - How to list imported modules?

Related QUESTION?