Find which python modules are being imported

后端 未结 4 794
有刺的猬
有刺的猬 2021-01-31 08:16

What\'s an easy way of finding all the python modules from a particular package that are being used in an application?

相关标签:
4条回答
  • 2021-01-31 08:37

    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

    0 讨论(0)
  • 2021-01-31 08:44

    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!-)

    0 讨论(0)
  • 2021-01-31 08:44

    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.)

    0 讨论(0)
  • 2021-01-31 08:45

    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.

    0 讨论(0)
提交回复
热议问题