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

后端 未结 3 1866
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    2020-12-18 17:12

    Get it from the globals dict in that case:

    def get_path():
        return globals()['__file__']
    

    Edit in response to the comment: given the following files:

    # a.py
    def get_path():
        return 'Path from a.py: ' + globals()['__file__']
    
    # b.py
    import a
    
    def get_path():
        return 'Path from b.py: ' + globals()['__file__']
    
    print get_path()
    print a.get_path()
    

    Running this will give me the following output:

    C:\workspace>python b.py
    Path from b.py: b.py
    Path from a.py: C:\workspace\a.py
    

    Next to the absolute/relative paths being different (for brevity, lets leave that out), it looks good to me.

提交回复
热议问题