在Python中,__file__双下划线变量可用于获取使用该变量的脚本的文件路径。有没有办法获取调用函数的脚本的文件路径?
我能够做到这一点的唯一方法是传递__file__给函数。我不想每次使用该功能时都这样做。我可以使用不同的双下划线变量吗?或者有没有办法检查命名空间中调用函数的绝对路径?
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)
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 …Run Code Online (Sandbox Code Playgroud)