如何获取导入某个包的python文件的路径?

时间:2019-07-04 09:00:17

标签: python module

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

1 个答案:

答案 0 :(得分:0)

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 b\n', ... ... ]
    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 ...