代码之家  ›  专栏  ›  技术社区  ›  prosseek

如何使用inspect从python中的被调用方获取调用方的信息?

  •  67
  • prosseek  · 技术社区  · 14 年前

    我需要从被呼叫者那里获得呼叫者信息(什么文件/什么行)。我了解到我可以将inpect模块用于此目的,但不完全是如何使用。

    如何通过inspect获取这些信息?或者有其他方法来获取信息吗?

    import inspect
    
    print __file__
    c=inspect.currentframe()
    print c.f_lineno
    
    def hello():
        print inspect.stack
        ?? what file called me in what line?
    
    hello()
    
    4 回复  |  直到 7 年前
        1
  •  81
  •   unutbu    7 年前

    inspect.currentframe().f_back inspect.getframeinfo

    import inspect
    
    def hello():
        previous_frame = inspect.currentframe().f_back
        (filename, line_number, 
         function_name, lines, index) = inspect.getframeinfo(previous_frame)
        return (filename, line_number, function_name, lines, index)
    
    print(hello())
    
    # (<frame object at 0x8ba7254>, '/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)
    
        2
  •  40
  •   Dmitry K.    10 年前

    inspect.stack

    import inspect
    
    def hello():
        frame,filename,line_number,function_name,lines,index = inspect.stack()[1]
        print(frame,filename,line_number,function_name,lines,index)
    hello()
    
        3
  •  1
  •   acue    8 年前

    spos

    pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

    spos=0 spos=1 spos=2

        4
  •  -5
  •   Jacob Cohen    8 年前