有没有办法以编程方式获取函数的行号和名称?
例如,我想将字符串列表传递给函数:
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/