Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list imported modules?

Tags:

python

People also ask

How do I show all Python modules?

To check all the installed Python modules, we can use the following two commands with the 'pip': Using 'pip freeze' command. Using 'pip list command.

Where are imported modules stored in Python?

Usually in /lib/site-packages in your Python folder. (At least, on Windows.) You can use sys. path to find out what directories are searched for modules.

How modules are imported in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


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.


Find the intersection of sys.modules with globals:

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

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.


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

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.


It's actually working quite good with:

import sys
mods = [m.__name__ for m in sys.modules.values() if m]

This will create a list with importable module names.