python - 如何获取导入某个包的python文件的路径?
问题描述
有 python 文件a.py
和b.py
. 并由b.py
导入。_ 如何获得in when运行的绝对路径?a.py
import b
a.py
b.py
a.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 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 ...
推荐阅读
- python - 如何从 python 守护进程运行 vimdiff
- cookies - 如果用户在 Quancast Choice 中选择更多选项,则横幅不可见
- android - 将过多的参数从 UI 传递到 UseCase Android Clean Architecture
- python - PyTorch:如何将包含整数和张量元组的列表中的元素相乘
- pyqt5 - pyqt vtk:如何去除边距?
- c++ - SIMD 聚集导致的分段错误?
- ruby-on-rails-5 - capybara 和 webdrivers gem 的只读文件系统错误
- ios - 在科尔多瓦 webview 上显示 UIButton
- asp.net - 如何在子文件夹中运行 asp.net 网站
- javascript - 在 `for`–`in` 循环中从对象访问属性会导致 `undefined`