【问题标题】:In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath?在python中,如果一个模块调用另一个模块的函数,该函数是否可以访问第一个模块的文件路径?
【发布时间】:2011-08-11 12:05:57
【问题描述】:

不将其作为参数传递...

例如。在 test1.py 中:

def function():
    print (?????)

在 test2.py 中

import test1

test1.function()

可以写吗??????所以运行 test2.py 会打印出“test2.py”或完整的文件路径? __file__ 会打印出“test1.py”。

【问题讨论】:

  • 将文件路径作为参数传递有什么问题?
  • 感觉不太优雅,而且还允许 test2.py 的编写者在该参数中输入一些愚蠢的东西(比如另一个文件名)。
  • sys._getframe().f_back.f_code.co_filename 怎么比传递参数更优雅?

标签: python module filepath


【解决方案1】:

这可以使用sys._getframe()来实现:

% cat test1.py
#!/usr/bin/env python

import sys

def function():
    print 'Called from within:', sys._getframe().f_back.f_code.co_filename

test2.py 看起来很像你的,但 import 固定:

% cat test2.py
#!/usr/bin/env python

import test1

test1.function()

试运行...

% ./test2.py 
Called from within: ./test2.py

注意:

CPython 实现细节:此函数应仅用于内部和专用目的。不保证在 Python 的所有实现中都存在。

【讨论】:

    【解决方案2】:

    你可以先获取调用者的框架。

    def fish():
        print sys._getframe(-1).f_code.co_filename
    

    【讨论】:

    • 打印 sys._getframe(1).f_code.co_filename 有效。这是你的意思吗? -1 仍然打印出 test1.py
    【解决方案3】:

    如果我理解正确,你需要的是:

    import sys
    print sys.argv[0]
    

    它给出:

    $ python abc.py 
    abc.py
    

    【讨论】:

    • 第一个参数可能不是文件名吗?
    【解决方案4】:

    这就是你要找的吗?

    test1.py:

    import inspect
    def function():
      print "Test1 Function"
      f = inspect.currentframe()
      try:
        if f is not None and f.f_back is not None:
          info = inspect.getframeinfo(f.f_back)
          print "Called by: %s" % (info[0],)
      finally:
        del f
    

    test2.py:

    import test1
    test1.function()
    
    $ python test2.py
    测试1功能
    调用者:test2.py

    【讨论】:

    • inspect.currentframe 有一个警告:它依赖于 python 实现并适用于 CPython。
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2020-12-09
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多