如何获取导入某个软件包的Python文件的路径



有Python文件a.pyb.pyb.pya.py中由import b导入。当a.py运行时,如何获得b.pya.py的绝对路径?

b.py

import os
import traceback

try: assert 0
except:
    st = traceback.format_stack()
     # format of st --> ['  File "filename", line 1, in <module>n    import bn', ... ... ]
    relative_p = st[0].split(',')[0].split(' ')[-1].split('"')[1]
    abs_path = os.path.abspath(relative_p)
    print(abs_path)
    # prints the importer's path, else if no importer, then itself's abs path
# rest of program goes here ...

最新更新