在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)
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
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句