Debugging: Get filename and line number from which a function is called?

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

Leave a Comment

techhipbettruvabetnorabahisbahis forumuedueduseduedusedusedueduseduseduedus