Class ModuleFinder trong module modulefinder xác định tập hợp module được import bởi một script. Module này có cả command line interface và programmatic interface.
Dùng script sau để demo:
# modfinder.py
import hello
try:
import trianglebrowser
import nomodule, mymodule
except ImportError:
pass
Command line interface
Lệnh sau hiển thị list module tìm thấy và không tìm thấy:
E:\python37>python -m modulefinder modfinder.py
Kết quả
Name File
---- ----
m __main__ modfinder.py
m hello hello.py
m math
m trianglebrowser trianglebrowser.py
Missing modules:
? mymodule imported from __main__
? nomodule imported from __main__
Programmatic interface
Class ModuleFinder cung cấp run_script() và report() để xác định module import bởi script.
- report(): In báo cáo ra stdout: list module import và path, cũng như module missing.
- run_script(): Phân tích nội dung file (phải chứa Python code).
- modules: Dictionary mapping tên module đến module object.
- badmodules: List module không load được.
Ví dụ
import modulefinder
modfind = modulefinder.ModuleFinder()
modfind.run_script('modfinder.py')
print('Modules loaded:')
for k, v in modfind.modules.items():
print(k, v)
print('not found:')
for i in modfind.badmodules.keys():
print(i)
Kết quả
Modules loaded:
__main__ Module('__main__', 'modfinder.py')
hello Module('hello', 'E:/python37\hello.py')
trianglebrowser Module('trianglebrowser', 'E:/python37\trianglebrowser.py')
math Module('math')
not found:
nomodule
mymodule