Return a list of imported Python modules used in a script?

后端 未结 13 2228
深忆病人
深忆病人 2020-11-30 00:23

I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which mod

13条回答
  •  迷失自我
    2020-11-30 01:12

    This works - using importlib to actually import the module, and inspect to get the members :

    #! /usr/bin/env python
    #
    # test.py  
    #
    # Find Modules
    #
    import inspect, importlib as implib
    
    if __name__ == "__main__":
        mod = implib.import_module( "example" )
        for i in inspect.getmembers(mod, inspect.ismodule ):
            print i[0]
    
    #! /usr/bin/env python
    #
    # example.py
    #
    import sys 
    from os import path
    
    if __name__ == "__main__":
        print "Hello World !!!!"
    

    Output :

    tony@laptop .../~:$ ./test.py
    path
    sys
    

提交回复
热议问题