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

向标准输出打印一份报告,列出脚本导入的模块及其路径,以及缺失或似乎缺失的模块。

run_script(pathname)

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

modules

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

ModuleFinder 的用法示例

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

import re, itertools

try:
    import baconhameggs
except ImportError:
    pass

try:
    import guido.python.ham
except ImportError:
    pass

将要输出 bacon.py 分析报告的脚本

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('bacon.py')

print('Loaded modules:')
for name, mod in finder.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()))

输出示例 (可能因体系结构而异)

Loaded modules:
_types:
copyreg:  _inverted_registry,_slotnames,__all__
re._compiler:  isstring,_sre,_optimize_unicode
_sre:
re._constants:  REPEAT_ONE,makedict,AT_END_LINE
sys:
re:  __module__,finditer,_expand
itertools:
__main__:  re,itertools,baconhameggs
re._parser:  _PATTERNENDERS,SRE_FLAG_UNICODE
array:
types:  __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs