modulefinder — Find modules used by a script¶
Source code:Lib/modulefinder.py
This module provides aModuleFinder class that can be used to determinethe set of modules imported by a script.modulefinder.py can also be run asa script, giving the filename of a Python script as its argument, after which areport of the imported modules will be printed.
- modulefinder.AddPackagePath(pkg_name,path)¶
Record that the package namedpkg_name can be found in the specifiedpath.
- modulefinder.ReplacePackage(oldname,newname)¶
Allows specifying that the module namedoldname is in fact the package namednewname.
- classmodulefinder.ModuleFinder(path=None,debug=0,excludes=[],replace_paths=[])¶
This class provides
run_script()andreport()methods to determinethe set of modules imported by a script.path can be a list of directories tosearch for modules; if not specified,sys.pathis used.debug sets thedebugging level; higher values make the class print debugging messages aboutwhat it’s doing.excludes is a list of module names to exclude from theanalysis.replace_paths is a list of(oldpath,newpath)tuples that willbe replaced in module paths.- report()¶
Print a report to standard output that lists the modules imported by thescript and their paths, as well as modules that are missing or seem to bemissing.
- run_script(pathname)¶
Analyze the contents of thepathname file, which must contain Pythoncode.
- modules¶
A dictionary mapping module names to modules. SeeExample usage of ModuleFinder.
Example usage ofModuleFinder¶
The script that is going to get analyzed later on (bacon.py):
importre,itertoolstry:importbaconhameggsexceptImportError:passtry:importguido.python.hamexceptImportError:pass
The script that will output the report of bacon.py:
frommodulefinderimportModuleFinderfinder=ModuleFinder()finder.run_script('bacon.py')print('Loaded modules:')forname,modinfinder.modules.items():print('%s: '%name,end='')print(','.join(list(mod.globalnames.keys())[:3]))print('-'*50)print('Modules not imported:')print('\n'.join(finder.badmodules.keys()))
Sample output (may vary depending on the architecture):
Loadedmodules:_types:copyreg:_inverted_registry,_slotnames,__all__re._compiler:isstring,_sre,_optimize_unicode_sre:re._constants:REPEAT_ONE,makedict,AT_END_LINEsys:re:__module__,finditer,_expanditertools:__main__:re,itertools,baconhameggsre._parser:_PATTERNENDERS,SRE_FLAG_UNICODEarray:types:__module__,IntType,TypeType---------------------------------------------------Modulesnotimported:guido.python.hambaconhameggs