Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you see the execution of a programme line by line in python?

Is there a way to see the details of the execution of a python file? I know that you can use logging, but obviously it would be unreasonable to set up the number of logs needed to see every line that's eventually executed. The python programme, of course, goes through the programme execution on a line by line basis, so to me, there must be a way to see the details of at the very least what line is being executed, and possibly where from.

I imagine that something like this would be possible:

lineno (27) 'test_file'
lineno (54) 'test_file'
lineno (12) 'test_file'
lineno (13) 'test_file'
like image 543
Jim Jam Avatar asked Dec 05 '25 20:12

Jim Jam


1 Answers

Debuggers are probably the better answer but you might also just use the trace module ( https://docs.python.org/3.6/library/trace.html ):

python -m trace -t yourscript.py

will display all lines your program is executing. If you just want to see how python steps through one script you could do.

python -m trace -t yourscript.py | grep yourscript.py

Please check following example and the output. Contents of tst.py:

sum = 0
for i in range(4):
    sum += i
print(sum)

And now the output you get:

$ python -m trace -t tst.py
 --- modulename: tst, funcname: <module>
tst.py(1): sum = 0
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(4): print(sum)
6
 --- modulename: trace, funcname: _unsettrace
trace.py(77):         sys.settrace(None)

like image 64
gelonida Avatar answered Dec 08 '25 10:12

gelonida



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!