有python文件a.py
和b.py
。 b.py
将a.py
导入import b
中。
a.py
运行时如何在b.py
中获得a.py
的绝对路径?
答案 0 :(得分:0)
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 ...