Python 获取调用函数的模块和行

Python 获取调用函数的模块和行,python,Python,有没有办法通过编程获得函数的行号和名称 例如,我想将字符串列表传递给函数: s = [calling_module, calling_function, line_number] report(s) 目前我只是手动将其全部放入: s = ["module abc", "func()", "line 22", "notes"] report(s) 但是我想知道python是否有一种自动的方式来填充模块名(我认为_uname _;可以做到这一点)、函数名和行号。有什么办法吗?您可能需要类似于回溯

有没有办法通过编程获得函数的行号和名称

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

s = [calling_module, calling_function, line_number]
report(s)
目前我只是手动将其全部放入:

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

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

您可能需要类似于
回溯的东西。extract\u stack()

>>def test():
...   打印“在功能中”
...   打印回溯。提取\u堆栈()
...
>>>
>>>测试()
在功能上
[('',1',无),('',3',测试,无]
尽管需要对结果进行分析。

使用模块函数。比如说,

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()
注意,使用

__name__ 

将返回包含报表的模块的名称,而上面的代码将显示调用报表的模块的名称。

虽然有合法的使用案例(错误报告,或实现类似Python 3的
super()
),但在使用它之前,请仔细考虑是否真的需要这些信息。这违反了程序中的正常信息流,如果您过度使用,可能会使代码更加混乱。使用它检查其他代码,学习。
from inspect import currentframe, getframeinfo, getmodulename

def report():
    f = getframeinfo(currentframe().f_back)
    print getmodulename(f.filename), f.lineno, f.function
__name__