31.6. modulefinder —查找脚本使用的模块

2.3 版的新Function。

源代码: Lib/modulefinder.py


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

  • modulefinder. AddPackagePath(* pkg_name path *)

    • 记录在指定的* path 中可以找到名为 pkg_name *的软件包。
  • modulefinder. ReplacePackage(* oldname newname *)

    • 允许指定名为* oldname 的模块实际上是名为 newname *的包。最常见的用法是处理_xmlplus软件包如何替换xml软件包。
    • class * modulefinder. ModuleFinder([* path = None debug = 0 excludes = [] replace_paths = [] *])
    • 此类提供run_script()report()方法来确定由脚本导入的模块集。 * path *可以是用于搜索模块的目录列表;如果未指定,则使用sys.path。 * debug *设置调试级别;较高的值使类打印有关其操作的调试消息。 * excludes *是要从分析中排除的模块名称的列表。 * replace_paths *是将在模块路径中替换的(oldpath, newpath)Tuples 的列表。
  • report ( )

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

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

31.6.1. 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.iteritems():
    print '%s: ' % name,
    print ','.join(mod.globalnames.keys()[:3])

print '-'*50
print 'Modules not imported:'
print '\n'.join(finder.badmodules.iterkeys())

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

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