How to get the file path of a module from a function executed but not declared in it?

后端 未结 3 1858
夕颜
夕颜 2020-12-18 16:29

If I want the path of the current module, I\'ll use __file__.

Now let\'s say I want a function to return that. I can\'t do:

def get_path         


        
3条回答
  •  隐瞒了意图╮
    2020-12-18 17:21

    This is how I would do it:

    import sys
    
    def get_path():
        namespace = sys._getframe(1).f_globals  # caller's globals
        return namespace.get('__file__')
    

提交回复
热议问题