Asked By – Amelio Vazquez-Reina
From what I have read, there are two ways to debug code in Python:
With a traditional debugger such as
ipdb. This supports commands such as
step-intoetc.), but you don’t have direct access to an IPython shell which can be extremely useful for object inspection.
Using IPython by embedding an IPython shell in your code. You can do
from IPython import embed, and then use
embed()in your code. When your program/script hits an
embed()statement, you are dropped into an IPython shell. This allows the full inspection of objects and testing of Python code using all the IPython goodies. However, when using
embed()you can’t step-by-step through the code anymore with handy keyboard shortcuts.
Is there any way to combine the best of both worlds? I.e.
- Be able to step-by-step through your code with handy pdb/ipdb keyboard shortcuts.
- At any such step (e.g. on a given statement), have access to a full-fledged IPython shell.
IPython debugging as in MATLAB:
An example of this type of “enhanced debugging” can be found in MATLAB, where the user always has full access to the MATLAB engine/shell, and she can still step-by-step through her code, define conditional breakpoints, etc. From what I have discussed with other users, this is the debugging feature that people miss the most when moving from MATLAB to IPython.
IPython debugging in Emacs and other editors:
I don’t want to make the question too specific, but I work mostly in Emacs, so I wonder if there is any way to bring this functionality into it. Ideally, Emacs (or the editor) would allow the programmer to set breakpoints anywhere on the code and communicate with the interpreter or debugger to have it stop in the location of your choice, and bring to a full IPython interpreter on that location.
Now we will see solution for issue: Step-by-step debugging with IPython
You can use IPython’s
%pdb magic. Just call
%pdb in IPython and when an error occurs, you’re automatically dropped to
ipdb. While you don’t have the stepping immediately, you’re in
This makes debugging individual functions easy, as you can just load a file with
%load and then run a function. You could force an error with an
assert at the right position.
%pdb is a line magic. Call it as
%pdb off or
%pdb 0. If called without argument it works as a toggle.
This question is answered By – sebastian
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0