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

ดึง Path ของ Python Module (__file__ attribute)

โมดูล Pure Python: Attribute __file__ เก็บ Path ของไฟล์ Source

ตัวอย่าง

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

Built-in Modules

  • ชี้ไป Shared Library (.so Linux/macOS, .pyd Windows)
  • Windows บางตัวไม่มี __file__
  • ไม่ใช่ Source Code

คำสั่ง python -v

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

แสดง Import ทุกตัวพร้อม Path ต้นทาง

Best Practice: ใช้ importlib.util.find_spec('module').origin (Python 3.4+) ได้ทั้ง Pure และ Built-in