Python: 如何获取调用函数的文件的绝对路径?
Python: How to get the absolute path of file where a function was called?
在Python中,__file__
双下划线变量可用于获取使用该变量的脚本的文件路径。有没有办法获取调用函数的脚本的文件路径?
我能够做到这一点的唯一方法是将 __file__
传递给函数。我不想每次使用该功能时都这样做。我可以使用不同的双下划线变量吗?或者有没有办法检查名称空间中调用函数的绝对路径?
这是我的:
definition.py的内容
def my_function(message, filepath_where_function_is_called):
print(message)
print("This function was called in:", filepath_where_function_is_called)
my_script.py的内容
from definition import my_function
my_function(message="Hello world!", filepath_where_function_is_called=__file__)
运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
这就是我想要的:
definition.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)
my_script.py的内容
from definition import my_function
my_function(message="Hello world!")
运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
您可以使用模块 traceback
来访问调用堆栈。调用堆栈的最后一个元素是最近调用的函数。倒数第二个元素是最近调用函数的调用者。
foo.py:
import traceback
def foo():
stack = traceback.extract_stack()
print(stack[-2].filename)
bar.py:
import foo
foo.foo()
在提示上:
import bar
# /path/to/bar.py
在Python中,__file__
双下划线变量可用于获取使用该变量的脚本的文件路径。有没有办法获取调用函数的脚本的文件路径?
我能够做到这一点的唯一方法是将 __file__
传递给函数。我不想每次使用该功能时都这样做。我可以使用不同的双下划线变量吗?或者有没有办法检查名称空间中调用函数的绝对路径?
这是我的:
definition.py的内容def my_function(message, filepath_where_function_is_called):
print(message)
print("This function was called in:", filepath_where_function_is_called)
my_script.py的内容
from definition import my_function
my_function(message="Hello world!", filepath_where_function_is_called=__file__)
运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
这就是我想要的:
definition.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)
my_script.py的内容
from definition import my_function
my_function(message="Hello world!")
运行my_script.py
$ python3 my_script.py
Hello world!
This function was called in: /path/to/my_script.py
您可以使用模块 traceback
来访问调用堆栈。调用堆栈的最后一个元素是最近调用的函数。倒数第二个元素是最近调用函数的调用者。
foo.py:
import traceback
def foo():
stack = traceback.extract_stack()
print(stack[-2].filename)
bar.py:
import foo
foo.foo()
在提示上:
import bar
# /path/to/bar.py