gpt4 book ai didi

python - 获取调用函数的模块和行

转载 作者:行者123 更新时间:2023-11-30 23:34:31 24 4
gpt4 key购买 nike

有没有办法以编程方式获取函数的行号和名称?

例如,我想将字符串列表传递给函数:

s = [calling_module, calling_function, line_number]
report(s)

目前我只是手动将其全部放入:

s = ["module abc", "func()", "line 22", "notes"]
report(s)

但我想知道 python 是否有一种自动方式来为我填写模块名称(我认为 __name__ 可以做到这一点)、函数名称和行号。有办法吗?

最佳答案

使用inspect模块功能。例如,

import inspect

def b():
f = inspect.currentframe()
current = inspect.getframeinfo(f)
caller = inspect.getframeinfo(f.f_back)
#caller = inspect.getframeinfo(inspect.getouterframes(f)[1][0])
print(__name__, current.filename, current.function, current.lineno, caller.function)

def a():
b()

a()

关于python - 获取调用函数的模块和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18045445/

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