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