Python debugging: get filename and line number from which a function is called?

前端 未结 4 1911
误落风尘
误落风尘 2020-12-24 01:12

I\'m currently building quite a complex system in Python, and when I\'m debugging I often put simple print statements in several scripts. To keep an overview I often also wa

4条回答
  •  清酒与你
    2020-12-24 01:33

    The function inspect.stack() returns a list of frame records, starting with the caller and moving out, which you can use to get the information you want:

    from inspect import getframeinfo, stack
    
    def debuginfo(message):
        caller = getframeinfo(stack()[1][0])
        print("%s:%d - %s" % (caller.filename, caller.lineno, message)) # python3 syntax print
    
    def grr(arg):
        debuginfo(arg)      # <-- stack()[1][0] for this line
    
    grr("aargh")            # <-- stack()[2][0] for this line
    

    Output:

    example.py:8 - aargh
    

提交回复
热议问题