How to find which Python modules are being imported from a package?

PythonServer Side ProgrammingProgramming

To find all the python modules from a particular package that are being used in an application, you can use the sys.modules dict. sys.modules is a dictionary mapping module names to modules. You can examine its keys to see imported modules.

For example,

>>> from datetime import datetime
>>> import sys
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', 'locale', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'datetime', 'sysconfig', 'operator', '__main__', 'types', 'encodings.encodings', 'abc', 'encodings.cp437', '_weakrefset', 'errno', 'encodings.codecs', 'backports', 'sre_constants', 're', '_abcoll', 'ntpath', '_codecs', 'zope', 'nt', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'mpl_toolkits', 'warnings', 'UserDict', 'encodings.cp1252', 'sys', 'codecs', 'os.path', '_functools', '_locale', 'signal', 'traceback', 'linecache', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']

You could also use python -v, which will emit messages about every imported module. For example, if you have the python code in hello.py, then,

$ python -v hello.py
raja
Updated on 01-Oct-2019 06:49:30

Advertisements