modulefinder —- 查找脚本使用的模块

源码:Lib/modulefinder.py


该模块提供了一个 ModuleFinder 类,可用于确定脚本导入的模块集。 modulefinder.py 也可以作为脚本运行,给出 Python 脚本的文件名作为参数,之后将打印导入模块的报告。

  • modulefinder.AddPackagePath(pkg_name, path)
  • 记录名为 pkg_name 的包可以在指定的 path 中找到。

  • modulefinder.ReplacePackage(oldname, newname)

  • 允许指定名为 oldname 的模块实际上是名为 newname 的包。

  • class modulefinder.ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[])

  • 该类提供 run_script()report() 方法,用于确定脚本导入的模块集。 path 可以是搜索模块的目录列表;如果没有指定,则使用 sys.pathdebug 设置调试级别;更高的值使类打印调试消息,关于它正在做什么。 excludes 是要从分析中排除的模块名称列表。 replace_paths 是将在模块路径中替换的 (oldpath, newpath) 元组的列表。

    • report()
    • 将报告打印到标准输出,列出脚本导入的模块及其路径,以及缺少或似乎缺失的模块。

    • runscript(_pathname)

    • 分析 pathname 文件的内容,该文件必须包含 Python 代码。

    • modules

    • 一个将模块名称映射到模块的字典。 请参阅 ModuleFinder 的示例用法

ModuleFinder 的示例用法

稍后将分析的脚本(bacon.py):

  1. import re, itertools
  2.  
  3. try:
  4. import baconhameggs
  5. except ImportError:
  6. pass
  7.  
  8. try:
  9. import guido.python.ham
  10. except ImportError:
  11. pass

将输出 bacon.py 报告的脚本:

  1. from modulefinder import ModuleFinder
  2.  
  3. finder = ModuleFinder()
  4. finder.run_script('bacon.py')
  5.  
  6. print('Loaded modules:')
  7. for name, mod in finder.modules.items():
  8. print('%s: ' % name, end='')
  9. print(','.join(list(mod.globalnames.keys())[:3]))
  10.  
  11. print('-'*50)
  12. print('Modules not imported:')
  13. print('\n'.join(finder.badmodules.keys()))

输出样例(可能因架构而异):

  1. Loaded modules:
  2. _types:
  3. copyreg: _inverted_registry,_slotnames,__all__
  4. sre_compile: isstring,_sre,_optimize_unicode
  5. _sre:
  6. sre_constants: REPEAT_ONE,makedict,AT_END_LINE
  7. sys:
  8. re: __module__,finditer,_expand
  9. itertools:
  10. __main__: re,itertools,baconhameggs
  11. sre_parse: _PATTERNENDERS,SRE_FLAG_UNICODE
  12. array:
  13. types: __module__,IntType,TypeType
  14. ---------------------------------------------------
  15. Modules not imported:
  16. guido.python.ham
  17. baconhameggs