Python:如何获取调用函数的文件的绝对路径?

ham*_*mad 5 python namespaces python-import python-3.x

在Python中,__file__双下划线变量可用于获取使用该变量的脚本的文件路径。有没有办法获取调用函数的脚本的文件路径?

我能够做到这一点的唯一方法是传递__file__给函数。我不想每次使用该功能时都这样做。我可以使用不同的双下划线变量吗?或者有没有办法检查命名空间中调用函数的绝对路径?

这就是我所拥有的:

定义.py 的内容
def my_function(message, filepath_where_function_is_called):
    print(message)
    print("This function was called in:", filepath_where_function_is_called)
Run Code Online (Sandbox Code Playgroud)my_script.py 的内容
from definition import my_function

my_function(message="Hello world!", filepath_where_function_is_called=__file__)
Run Code Online (Sandbox Code Playgroud) 运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
Run Code Online (Sandbox Code Playgroud)

这就是我要的:

定义.py 的内容
def my_function(message):
    print(message)
    filepath_where_function_is_called = ...  # I don't know this piece 
    print("This function was called in:", filepath_where_function_is_called)
Run Code Online (Sandbox Code Playgroud)my_script.py 的内容
from definition import my_function

my_function(message="Hello world!")
Run Code Online (Sandbox Code Playgroud) 运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
Run Code Online (Sandbox Code Playgroud)

DYZ*_*DYZ 8

您可以使用模块traceback来访问调用堆栈。调用堆栈的最后一个元素是最近调用的函数。倒数第二个元素是最近调用的函数的调用者。

foo.py:

import traceback
def foo(): 
    stack = traceback.extract_stack()
    print(stack[-2].filename)
Run Code Online (Sandbox Code Playgroud)

酒吧.py:

import foo
foo.foo()
Run Code Online (Sandbox Code Playgroud)

在提示符上:

import bar
# /path/to/bar.py
Run Code Online (Sandbox Code Playgroud)