gpt4 book ai didi

Python 自省(introspection) - 如何从函数内部检查当前模块/调用行

转载 作者:太空狗 更新时间:2023-10-29 22:06:02 26 4
gpt4 key购买 nike

我有一个函数:

# 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

最佳答案

访问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 自省(introspection) - 如何从函数内部检查当前模块/调用行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5326539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com