1

How do I track Python code from start to finish? That shows the entire flow of execution, from which function is called first, which operations are performed, to the end of the entire flow.

Look at this example code, it receives an operation type (addition or subtraction) and two values ​​(x and y), executes these two values ​​according to the operation and at the end displays a message:

def calc(op, x, y):
    if op == 'sum':
        return x + y
    elif op == 'subtraction':
        return x - y


def msg(op, x, y):
    if op == 'sum':
        result = calc(op, x, y)
        return "The result of the sum is: " + str(result)
    elif op == 'subtraction':
        result = calc(op, x, y)
        return "The result of the subtraction is: " + str(result)


if __name__ == '__main__':
    my_sum = msg('sum', 3, 2)
    print(my_sum)

So this "tracking from start to finish" would look something like this:

  1. Line 17: if __name__ == '__main__':
  2. Line 18: my_sum = msg('sum', 3, 2)
  3. Line 8: def msg(op, x, y):
  4. Line 9: if op == 'sum':
  5. Line 10: result = calc(op, x, y)
  6. Line 1: def calc(op, x, y):
  7. Line 2: if op == 'sum':
  8. Line 3: return x + y
  9. Line 11: return "The result of the sum is:" + str(result)
  10. Line 19: print(my_sum)

And at the end it returns the message "The result of the sum is: 5".

  • This is called Debugger. Google is your friend. And this question does not belong on StackOverflow. It asks for a library/tool, which is explicitly disallowed. – MegaIng Mar 29 '20 at 00:12
  • 1
    I know what debugging is, but I would like to know if there are more sophisticated ways of doing this "tracking" – Eduardo Daltro Mar 29 '20 at 00:27
  • I tagged it as a duplicate as the old thread from 2010 is still extremely helpful, and solves this problem as mentioned by the solution below. I meant to flag it so we could vote but it went straight to dupe. Apologies if that causes confusion :) – Torxed May 11 '22 at 18:18

1 Answers1

0

You can profile your Python script. Python itself, in the standard library, have [profilers] (https://docs.python.org/3/library/profile.html#introduction-to-the-profilers) to profile and trace your script. Also, there are a visual library called [Tuna] (https://github.com/nschloe/tuna) that can help you to graphically profile your script. Maybe, you can use another tool, to easy trace your entire script, called [KCacheGrind] (https://kcachegrind.github.io/html/Home.html), that shows a visually oriented trace of the function calls.

jrborba
  • 148
  • 1
  • 7