如何在python中识别调用函数的文件名?

2024-09-28 03:15:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个服务器.py它包含一个函数和其他文件,如requestor1.py requestor2.py。。。。请求者.py你知道吗

你知道吗服务器.py包含函数:

def callmeforhelp()
    return "I am here to help you out!"

并且requestor1.py文件调用函数callmeforhelp(),并且它具有从中调用函数所需的导入服务器.py你知道吗

有没有办法让我服务器.py知道哪个文件在调用它吗?你知道吗

类似如下:

当requestor1.py调用函数时,则:

def callmeforhelp()
    print "Now I am being called by : "+caller // caller must contain the value as requestor1.py or even full path of requestor1.py
    return "I am here to help you out!"

Tags: 文件to函数py服务器youreturnhere
2条回答

以下是获取调用者的本地属性的方法:

import sys

def callmeforhelp():
    print("Called from", sys._getframe(1).f_locals['__file__'])

这是CPython的一个特性,不能保证在其他语言实现中存在。你知道吗

server文件中尝试:

import inspect

def callmeforhelp():
    result = inspect.getouterframes(inspect.currentframe(), 2)
    print("Caller is: " + str(result[1][1]))

相关问题 更多 >

    热门问题