18

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.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
user11869
  • 1,083
  • 2
  • 14
  • 29

6 Answers6

29

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

Michael Hoffman
  • 32,526
  • 7
  • 64
  • 86
  • Sorry for all the confusion, I should be more clear. The reason I asked is that I want to write a program that can execute a python source code line by line, and in between lines I want to run my own stuff and be able to access the current namespace of the source code being executed. – user11869 Oct 06 '11 at 23:28
  • 2
    I'd go with the python debugger for exactly that. It can be invoked from within code and not just from the command line. Have a look at the source code of Pdb class. The docs say its extensible, so you should be able to customize it to do what you want. – Mark Gemmill Oct 06 '11 at 23:50
3

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

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

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
1

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

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.

Ali
  • 18,665
  • 21
  • 103
  • 138
0

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