What\'s an easy way of finding all the python modules from a particular package that are being used in an application?
sys.modules
is a dictionary mapping module names to modules. You can examine its keys to see imported modules.
See: http://docs.python.org/library/sys.html#sys.modules
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!-)
A real simple method is to delete all .pyc files from the package or folder, and then run the application. Once you've played a bit, do a directory listing and see which files have .pyc files now. Those are modules which were imported by the application.
(Note: the __main__
module, whichever one you invoke as the "main" script, never gets compiled, so you should not expect to see a .pyc file for it unless something imported it from within the application. This is often a sign of a problem if it does happen.)
I think modulefinder is what you're looking for. You can use modulefinder.py
directly, running it as a script as is described there, or you can import the module and then create a report using the modulefinder.ModuleFinder
class.