17
votes

Given a Python source code, is it possible to run the code line by line, as if you were debugging?

And when it comes to a function call, I would like to 'step into' the function also.

6
What you are describing, is debugging. Is that what you want asking, how do I debug a python program? - John Keyes
Have you considered pdb, which comes with Python? - Greg Hewgill
Python code does run line by line. And it does step into functions when they are called. How else would it execute it? - Chris Morgan
sorry for the confusion, I'm not talking about debugging, see my comment below. - user11869
Even after reading that, it still sounds like you want to debug it. - John Keyes

6 Answers

25
votes

python -m pdb <script.py> will run the script in the Python debugger.

3
votes

If you're using PyCharm, you can change the keyboard shortcut settings -

Settings>>Keymap>>Other>>Execute selection in console

If you have migrated from R, changing this to Ctrl+Enter would help you run the code line by line.

2
votes

I'd suggest looking at Eclipse and PyDev for debugging. I imagine there are many alternatives though.

1
votes

What you are describing, is debugging. So here is the source code of python debugger used by most code editors (like vs code, virtual studio, PyCharm, PyDev, etc). Have a look at this https://github.com/fabioz/PyDev.Debugger

Note that this is only used for python code debugging not for other languages

or, The better option that you have to understand how debuggers work is to look at this article https://opensource.com/article/19/8/debug-python

0
votes

Have a look at ipython, you should be able to use a combination of pdb and ipython, like loading pdb inside ipython to achieve what you need.

0
votes

For most instances, the debugging tools mentioned in other answers are all you should need - but if you really want to follow / control your program line-by-line, I think you're looking for

sys.settrace(tracefunc) - where tracefunc is a python function that will be called for a range of different events - 'call', 'line', 'return', 'exception' or 'opcode'. For the OP, the 'line' event is the interesting one here, being fired immediately before the execution of the next line of code.

Example:

def trace_dispatch(frame, event, arg):
    if event == 'line':
        record_line_execution(frame)

sys.settrace(trace_dispatch)

Incidentally - I'm pretty sure that this is the mechanism that the debugging tools use to work their magic