jason
jason

Reputation: 4801

getting the module and line that a function was called from

Is there a way to programatically get the line number and name of a function?

For example, I want to pass a list of strings to a function :

s = [calling_module, calling_function, line_number]
report(s)

Currently I just put it all in manually :

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

But I would like to know if there is an automatic way for python to fill in the module name (I think __name__ does that), function name and line number for me. Is there a way?

Upvotes: 1

Views: 330

Answers (3)

falsetru
falsetru

Reputation: 369054

Use inspect module functions. For example,

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()

Upvotes: 2

Peter de Rivaz
Peter de Rivaz

Reputation: 33509

from inspect import currentframe, getframeinfo, getmodulename

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

Note that using

__name__ 

will return the name of the module containing report, while the code above will show the name of the module that called report.

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47988

You may want something along the lines of traceback.extract_stack():

>>> def test():
...   print "In Function"
...   print traceback.extract_stack()
...
>>>
>>> test()
In Function
[('<stdin>', 1, '<module>', None), ('<stdin>', 3, 'test', None)]

Though the results would need to be parsed.

Upvotes: 1

Related Questions