Get the __file__ of the function one level up in the stack

泪湿孤枕 提交于 2019-12-01 01:07:54

问题


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)

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")

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?


回答1:


This should do it:

inspect.getfile(sys._getframe(1))

sys._getframe(1) gets the caller frame, inspect.getfile(...) retrieves the filename.



来源:https://stackoverflow.com/questions/11757801/get-the-file-of-the-function-one-level-up-in-the-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!