小编ham*_*mad的帖子

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

在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 …
Run Code Online (Sandbox Code Playgroud)

python namespaces python-import python-3.x

5
推荐指数
1
解决办法
1561
查看次数

标签 统计

namespaces ×1

python ×1

python-3.x ×1

python-import ×1