This document is for an old version of Python that is no longer supported. You should upgrade and read the Python 当前稳定版本的文档.

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

2.3 新版功能.

源码： Lib/modulefinder.py

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

`modulefinder.``AddPackagePath`(pkg_name, path)

  记录名为 pkg_name 的包可以在指定的 path 中找到。

`modulefinder.``ReplacePackage`(oldname, newname)

  Allows specifying that the module named oldname is in fact the package named newname. The most common usage would be to handle how the `_xmlplus` package replaces the `xml` package.

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

  This class provides `run_script()` and `report()` methods to determine the set of modules imported by a script. path can be a list of directories to search for modules; if not specified, `sys.path` is used. debug sets the debugging level; higher values make the class print debugging messages about what it’s doing. excludes is a list of module names to exclude from the analysis. replace_paths is a list of `(oldpath, newpath)` tuples that will be replaced in module paths.

  `report`()

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

  `run_script`(pathname)

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

  `modules`

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

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

输出样例（可能因架构而异）:

    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