modulefinder — 스크립트가 사용하는 모듈 찾기

modulefinder — 스크립트가 사용하는 모듈 찾기

modulefinder 모듈은 스크립트가 임포트하는 모듈 집합을 알아내는 데 쓸 수 있는 ModuleFinder 클래스를 제공해요. modulefinder.py는 스크립트로도 실행할 수 있는데, Python 스크립트의 파일 이름을 인자로 주면 임포트된 모듈의 리포트가 출력돼요.

출처: 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.path가 사용돼요. debug는 디버깅 수준을 설정하고, 값이 높을수록 무슨 일을 하는지에 대한 디버깅 메시지를 출력해요. excludes는 분석에서 제외할 모듈 이름 리스트예요. replace_paths는 모듈 경로에서 치환될 (oldpath, newpath) 튜플의 리스트예요.

report()

스크립트가 임포트한 모듈과 그 경로, 그리고 없거나 없는 것처럼 보이는 모듈을 나열한 리포트를 표준 출력으로 출력해요.

run_script(pathname)

Python 코드를 담은 pathname 파일의 내용을 분석해요.

modules

모듈 이름을 모듈로 매핑하는 딕셔너리예요.

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