Python自省-如何从函数中检查当前模块/调用行 [英] Python introspection - how to check current module / line of call from within function
本文介绍了Python自省-如何从函数中检查当前模块/调用行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个功能:
# 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
推荐答案
访问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))
这篇关于Python自省-如何从函数中检查当前模块/调用行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文