modulefinder --- 搜尋腳本所使用的模組 — Python 3.14.6 說明文件
此模組提供了一個 ModuleFinder 類別,可用於確定腳本引入的模組集合。modulefinder.py 也可以作為腳本運行,其將 Python 腳本的檔案名稱作為它的引數,並在之後會列印出引入模組的報告。
- modulefinder.AddPackagePath(pkg_name, path)¶
記錄在指定的 path 中可以找到名為 pkg_name 的套件。
- modulefinder.ReplacePackage(oldname, newname)¶
允許指定名為 oldname 的模組實際上是名為 newname 的套件。
- class modulefinder.ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[])¶
此類別提供
run_script()和report()方法來決定腳本引入的模組集合。path 可以是搜尋模組的目錄串列;如果未指定,則使用sys.path。debug 設定偵錯等級;較高的值可使類別列印有關其即將執行之操作的偵錯訊息。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('載入模組:') for name, mod in finder.modules.items(): print('%s: ' % name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('-'*50) print('模組沒有被引入:') print('\n'.join(finder.badmodules.keys()))
範例輸出(可能因架構而異):
載入模組: _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 --------------------------------------------------- 模組沒有被引入: guido.python.ham baconhameggs