How to enumerate all imported modules?
E.g. I would like to get ['os', 'sys']
from this code:
import os
import sys
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.
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.
This code lists modules imported by your module:
import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]
It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.
It won't list the sys
module or modules imported from it.
Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:
#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()
which produces:
Name File
---- ----
...
m token /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...
.. suitable for grepping or what have you. Be warned, it's long!
I like using a list comprehension in this case:
>>> [w for w in dir() if w == 'datetime' or w == 'sqlite3']
['datetime', 'sqlite3']
# To count modules of interest...
>>> count = [w for w in dir() if w == 'datetime' or w == 'sqlite3']
>>> len(count)
2
# To count all installed modules...
>>> count = dir()
>>> len(count)
ipython --pylab
) python interpreter is launched with predefined modules loaded. Question remains, for how to know the alias used o_O – yota