Reputation: 347
How can I print every function/method call ?
I have tried to use : python -m trace --trace
but it prints also the function inner code... I just want functions names that were called.
using traceback in code prints the last function called before calling the command itself, and the code contains many classes...
Upvotes: 5
Views: 6323
Reputation: 1709
here is the code with name player.py
.
# player.py
def foo():
pass
def bar():
foo()
def car():
bar()
pass
car()
executed the command from the terminal like $python -m trace -T player.py
and it gives me the following output. you can also use for --trackcalls
instead of -T
for the same output. And that command Display the calling relationships exposed by running the program.
calling relationships:
*** /usr/lib/python2.7/trace.py ***
trace.Trace.runctx -> trace._unsettrace
--> player.py
trace.Trace.runctx -> player.<module>
*** player.py ***
player.<module> -> player.car
player.bar -> player.foo
player.car -> player.bar
Hope this will help.
Update 1:
the above command display the function's relationship.
For tracing the function we can use traceback
module. In this module traceback.print_stack()
print the function depending on the execution. But we have to keep in mind that in which method we write the traceback.print_stack()
it will only print the trace of that function. I will give you an example.
import traceback
def foo():
car()
pass
def bar():
foo()
def car():
traceback.print_stack()
pass
bar()
and if we run this we can see the following output.
File "D:/python_practice36/player.py", line 10, in <module>
bar()
File "D:/python_practice36/player.py", line 6, in bar
foo()
File "D:/python_practice36/player.py", line 3, in foo
car()
File "D:/python_practice36/player.py", line 8, in car
traceback.print_stack()
if we call the traceback.print_stack()
in foo()
then we can see the traceback upto foo
.
import traceback
def foo():
car()
traceback.print_stack()
pass
def bar():
foo()
def car():
pass
bar()
and the output is
File "D:/python_practice36/player.py", line 10, in <module>
bar()
File "D:/python_practice36/player.py", line 7, in bar
foo()
File "D:/python_practice36/player.py", line 4, in foo
traceback.print_stack()
Upvotes: 2
Reputation: 81594
You may find -l
useful.
main.py:
def foo():
pass
def bar():
pass
foo()
bar()
Doing
$ python -m trace -l main.py
outputs
functions called:
filename: C:\Python34\lib\trace.py, modulename: trace, funcname: _unsettrace
filename: main.py, modulename: main, funcname: <module>
filename: main.py, modulename: main, funcname: bar
filename: main.py, modulename: main, funcname: foo
Depending on the number of functions you have, you may find a decorator more suitable:
def print_deco(func):
def inner(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return inner
@print_deco
def foo():
pass
@print_deco
def bar():
pass
foo()
bar()
# foo
# bar
Upvotes: 8