Python内省 - 如何从函数内检查当前模块/调用行

时间:2011-03-16 14:13:05

标签: python introspection

我有一个功能:

# 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

3 个答案:

答案 0 :(得分:13)

访问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))

答案 1 :(得分:3)

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

答案 2 :(得分:1)

使用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模块非常棒,因为模块的用户可以禁用警告,或将其转换为完全可检查的异常。