确定函数的执行位置?

wal*_*tes 6 python

我该如何定义一个函数,where它可以告诉它在哪里执行,没有传入参数?〜/ app /中的所有文件

a.py:

def where():
    return 'the file name where the function was executed'
Run Code Online (Sandbox Code Playgroud)

b.py:

from a import where
if __name__ == '__main__':
    print where() # I want where() to return '~/app/b.py' like __file__ in b.py
Run Code Online (Sandbox Code Playgroud)

c.py:

from a import where
if __name__ == '__main__':
    print where() # I want where() to return '~/app/c.py' like __file__ in c.py
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 12

您需要使用以下方法查找调用堆栈inspect.stack():

from inspect import stack

def where():
    caller_frame = stack()[1]
    return caller_frame[0].f_globals.get('__file__', None)
Run Code Online (Sandbox Code Playgroud)

甚至:

def where():
    caller_frame = stack()[1]
    return caller_frame[1]
Run Code Online (Sandbox Code Playgroud)