andrea-f
andrea-f

Reputation: 1055

How can I trace the functions call stack in a Python script?

I am trying to debug some code written long ago, and due to the scarce documentation would like a way to trace the functions being called from execution to final output, possibly with which parameters they were called with. A sort of sys.traceback but in the case of no errors. It would also be nice to get the report as a HTML or another exportable format. Something along the lines of:

main()->class->run()->getData()->saveData()

I already looked at Can I trace all the functions/methods executing in a python script? but it doesn't answer the question as functions are not reportd.

Upvotes: 1

Views: 1272

Answers (2)

mhbashari
mhbashari

Reputation: 482

probably you need settrace function

CODE

import sys

def traceit(frame, event, arg):
    if event == "call":
        co = frame.f_code
        func_name = co.co_name
        print("event:", event,"of function",func_name)
    return traceit

def main():
    print ("In main")
    for i in range(5):
        print (i, i*3)
    print ("Done.")


sys.settrace(traceit)
main()

OUT PUT

event: call of function main
In main
0 0
1 3
2 6
3 9
4 12
Done.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249103

Try using pycallgraph or another "call graph" visualization tool.

Upvotes: 1

Related Questions