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

หาตำแหน่ง Source Code ของ Python Module (__file__)

โมดูล Pure Python: ดู module.__file__

ตัวอย่าง

>>> import mymodule
>>> mymodule.__file__
'C:/Users/Ayush/mymodule.py'

Built-in Modules (C Extension)

  • __file__ ชี้ไป .so (Linux/macOS) หรือ .pyd (Windows)
  • Windows บางกรณีไม่มี __file__
  • Source ไม่อยู่ในไฟล์นั้น (อยู่ใน CPython Source Tree)

คำสั่ง Verbose: ดู Import ทั้งหมด

$ python -v hello.py
# import os
# import sys
# from datetime import datetime
# ...

บอกว่า Import อะไร จากไฟล์ไหน ทุกบรรทัด

เคล็ดลับ: ใช้ import inspect; print(inspect.getfile(module)) ได้ผลเหมือน __file__ แต่ Handle Built-in ดีกว่า