确定在哪里执行功能?

发布于 2021-01-29 16:21:49

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

a.py:

def where():
    return 'the file name where the function was executed'

b.py:

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

c.py:

from a import where
if __name__ == '__main__':
    print where() # I want where() to return '~/app/c.py' like __file__ in c.py
关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您需要使用来查找调用堆栈inspect.stack()

    from inspect import stack
    
    def where():
        caller_frame = stack()[1]
        return caller_frame[0].f_globals.get('__file__', None)
    

    甚至:

    def where():
        caller_frame = stack()[1]
        return caller_frame[1]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看