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

梦想的初衷 提交于 2019-12-06 14:56:16

问题


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():
    return __file__

Because it will return the path of the module the function has been declared in.

I need it to work even if the function is not called at the root of the module but at any level of nesting.


回答1:


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__')



回答2:


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.




回答3:


I found a way to do it with the inspect module. I'm ok with this solution, but if somebody find a way to do it without dumping the whole stacktrace, it would be cleaner and I would accept his answer gratefully:

def get_path():
    frame, filename, line_number, function_name, lines, index =\
        inspect.getouterframes(inspect.currentframe())[1]
    return filename


来源:https://stackoverflow.com/questions/13137141/how-to-get-the-file-path-of-a-module-from-a-function-executed-but-not-declared-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!