python 获取调用函数的名字和行号

现有两个文件:

a.py

from inspect import currentframe, stack, getmodule

def write(msg):
    f_current_line = str(currentframe().f_back.f_lineno)  # 哪一行调用的此函数
    print('line number:',f_current_line)
    mod = getmodule(stack()[1][0])     # 调用函数的信息 
    module_name = mod.__name__   # 函数名
    print('module info:',mod)
    print('module name:',module_name)

b.py

from a import write

def test():
    write('lllllll')

test()

执行b.py

line number: 4
module info: <module '__main__' from 'C:\\Users\\wang\\Desktop\\b.py'>
module name: __main__
posted @ 2021-02-25 16:53  wztshine  阅读(1465)  评论(1编辑  收藏  举报