Question
Find which python modules are being imported
What's an easy way of finding all the python modules from a particular package that are being used in an application?
45 22262
45
Question
What's an easy way of finding all the python modules from a particular package that are being used in an application?
Solution
sys.modules
is a dictionary mapping module names to modules. You can examine its keys to see imported modules.
Solution
You could use python -v
, which will emit messages about every imported module:
$ echo 'print "hello world"' > helo.py
$ python -v helo.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.py
import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.pyc
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py
import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.pyc
import posix # builtin
# /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py
import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc
...and so on, and so forth. Of course you can later grep
the modules of interest from among this large list!-)