首页 > 解决方案 > 如何获取导入某个包的python文件的路径?

问题描述

有 python 文件a.pyb.py. 并由b.py导入。_ 如何获得in when运行的绝对路径?a.pyimport ba.pyb.pya.py

标签: pythonmodule

解决方案


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 ...

推荐阅读