【问题标题】:Python introspection - how to check current module / line of call from within functionPython自省 - 如何从函数内检查当前模块/调用行
【发布时间】:2011-03-16 14:13:05
【问题描述】:

我有一个函数:

# utils.py
def hello(name='World'):
    # Detect where I'm being called from.
    print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno))
    # ``mod`` and ``lineno`` on previous line would have been set in real use.

我导入该函数并在其他地方运行它

# other.py (this comment at line # 138)
from utils import hello
hello('Johnny')  # From inside ``hello`` I want to be able to detect that this
# was called from other.py at line # 140

【问题讨论】:

    标签: python introspection


    【解决方案1】:

    访问inspect.currentframe()的封闭框架:

    import inspect
    
    def hello(name='World'):
        f = inspect.currentframe().f_back
        mod = f.f_code.co_filename
        lineno = f.f_lineno
        print('Hi, %s. You called this from %s at line # %d.' %
              (name, mod, lineno))
    

    【讨论】:

      【解决方案2】:

      traceback 模块让您可以提取堆栈,这样您就可以看到您是如何到达当前堆栈帧的。如果你愿意,你可以扩展它来打印调用者的调用者,只要你喜欢:

      import traceback
      
      def _trace():
          stack = traceback.extract_stack()[-3:-1]
          path, line, in_func, _instr = stack[0]
          print 'called from %s in func %s at line %s' % (path, in_func, line)
      
      def bar():
          _trace()
      
      def foo():
          bar()
          baz()
      
      def baz():
          bar()
      
      bar()
      foo()
      

      输出:

      called from hello.py in func <module> at line 20
      called from hello.py in func foo at line 14
      called from hello.py in func baz at line 18
      

      【讨论】:

        【解决方案3】:

        使用warnings 模块。

        import warnings
        
        def test(where):
            warnings.warn('hi from test', stacklevel=2)
        
        def foo():
            test('inside foo')
        
        test('from main module')
        foo()
        

        结果:

        /tmp/test.py:9: UserWarning: hi from test
          test('from main module')
        /tmp/test.py:7: UserWarning: hi from test
          test('inside foo')
        

        检查行号。使用 warnings 模块非常棒,因为您的模块的用户可以禁用警告,或者将它们变成完全可检查的异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-27
          • 1970-01-01
          相关资源
          最近更新 更多