开发者

run python source code line by line

Given a Python source code, is it possible to run th开发者_开发问答e 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.


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


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.


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜