Get the __file__ of the function one level up in the stack(获取堆栈中上一级函数的 __file__)
问题描述
我发现我经常使用这种模式:
I've found that I'm using this pattern a lot :
os.path.join(os.path.dirname(__file__), file_path)
所以我决定在一个包含许多这样的小实用程序的文件中放入一个函数:
so I've decided to put in a function in a file that has many such small utilities:
def filepath_in_cwd(file_path):
return os.path.join(os.path.dirname(__file__), file_path)
问题是,__file__ 返回 current 文件,因此返回当前文件夹,我错过了重点.我可以做这个丑陋的 hack(或者继续按原样编写模式):
The thing is, __file__ returns the current file and therefore the current folder, and I've missed the whole point. I could do this ugly hack (or just keep writing the pattern as is):
def filepath_in_cwd(py_file_name, file_path):
return os.path.join(os.path.dirname(py_file_name), file_path)
然后对它的调用将如下所示:
and then the call to it will look like this:
filepath_in_cwd(__file__, "my_file.txt")
但如果我有办法获取堆栈中上一层的函数的 __file__ ,我会更喜欢它.有没有办法做到这一点?
but I'd prefer it if I had a way of getting the __file__ of the function that's one level up in the stack. Is there any way of doing this?
推荐答案
应该这样做:
inspect.getfile(sys._getframe(1))
sys._getframe(1) 获取调用者框架,inspect.getfile(...) 检索文件名.
sys._getframe(1) gets the caller frame, inspect.getfile(...) retrieves the filename.
这篇关于获取堆栈中上一级函数的 __file__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取堆栈中上一级函数的 __file__
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
