【问题标题】:Get the __file__ of the function one level up in the stack获取堆栈中上一级函数的 __file__
【发布时间】:2012-07-30 06:19:53
【问题描述】:

我发现我经常使用这种模式:

os.path.join(os.path.dirname(__file__), file_path)

所以我决定在一个包含许多这样的小实用程序的文件中放入一个函数:

def filepath_in_cwd(file_path): 
    return os.path.join(os.path.dirname(__file__), file_path)

问题是,__file__ 返回 current 文件,因此返回当前文件夹,我错过了重点。我可以做这个丑陋的 hack(或者继续按原样编写模式):

def filepath_in_cwd(py_file_name, file_path): 
    return os.path.join(os.path.dirname(py_file_name), file_path)

然后对它的调用将如下所示:

filepath_in_cwd(__file__, "my_file.txt")

但如果我有办法获得堆栈中上一层的函数的__file__,我会更喜欢它。有没有办法做到这一点?

【问题讨论】:

    标签: python stack filepath


    【解决方案1】:

    应该这样做:

    inspect.getfile(sys._getframe(1))
    

    sys._getframe(1) 获取调用者框架,inspect.getfile(...) 检索文件名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2017-07-14
      • 2010-11-24
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      相关资源
      最近更新 更多