Python introspection - how to check current module / line of call from within function

限于喜欢 提交于 2020-01-01 05:28:28

问题


I have a function:

# 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.

I import that function and run it elsewhere

# 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

回答1:


Access the enclosing frame of 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:


The traceback module lets you extract the stack, so you can see how you reached the current stack frame. If you want you can extend this to print the caller-of-caller, as far up the stack as you like:

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()

Output:

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:


Use the warnings module.

import warnings

def test(where):
    warnings.warn('hi from test', stacklevel=2)

def foo():
    test('inside foo')

test('from main module')
foo()

Results:

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

Check the line numbers. Using the warnings module is great because the user of your module can disable warnings, or turn them into fully inspectable exceptions.



来源:https://stackoverflow.com/questions/5326539/python-introspection-how-to-check-current-module-line-of-call-from-within-fu

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