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

后端 未结 13 2219
深忆病人
深忆病人 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:01

    I was looking for something similar and I found a gem in a package called PyScons. The Scanner does just what you want (in 7 lines), using an import_hook. Here is an abbreviated example:

    import modulefinder, sys
    
    class SingleFileModuleFinder(modulefinder.ModuleFinder):
    
        def import_hook(self, name, caller, *arg, **kwarg):
            if caller.__file__ == self.name:
                # Only call the parent at the top level.
                return modulefinder.ModuleFinder.import_hook(self, name, caller, *arg, **kwarg)
    
        def __call__(self, node):
    
            self.name = str(node)
    
            self.run_script(self.name)
    
    if __name__ == '__main__':
        # Example entry, run with './script.py filename'
        print 'looking for includes in %s' % sys.argv[1]
    
        mf = SingleFileModuleFinder()
        mf(sys.argv[1])
    
        print '\n'.join(mf.modules.keys())
    

提交回复
热议问题