Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การค้นหาโมดูลที่ใช้โดยสคริปต์ Python (modulefinder)


คลาส ModuleFinder ในโมดูล 'modulefinder' สามารถกำหนดชุดของโมดูลที่ถูก import โดยสคริปต์เฉพาะได้ โมดูลนี้มี command line interface และ programmatic interface

สำหรับการสาธิตฟังก์ชัน ใช้สคริปต์ต่อไปนี้

#modfinder.py import hello try: import trianglebrowser import nomodule,mymodule except ImportError: pass

Command line interface

คำสั่งต่อไปนี้แสดงรายการโมดูลที่พบและไม่พบ

E:\python37>python -m modulefinder modfinder.py

ผลลัพธ์

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

ModuleFinder คลาสในโมดูลนี้มีเมธอด run_script() และ report() เพื่อกำหนดชุดโมดูลที่ถูก import โดยสคริปต์

report()

เมธอดนี้พิมพ์รายงานไปยัง standard output ที่แสดงโมดูลที่ถูก import โดยสคริปต์และ path ของพวกมัน รวมถึงโมดูลที่หายไปหรือดูเหมือนจะหายไป

run_script()

เมธอดนี้วิเคราะห์เนื้อหาของไฟล์ที่กำหนด ซึ่งต้องมีโค้ด Python

modules

นี่คือ dictionary mapping ชื่อโมดูลไปยังโมดูล

badmodules

นี่คือลิสต์ของโมดูลที่โหลดไม่ได้

ตัวอย่าง


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)

ผลลัพธ์

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