开发者

ipython -pylab debugging: Can I stop the execution at a specific line and drop into the shell?

When writing python code (mostly numpy + matplotlib), I usually just type the code in vim and run the program to test it:

python2 foo.py

Occasionally, when this is not sufficient and I need to inspect the problem more thoroughly, I just launch the program in ipython: ipython -pylab foo.py, and then inspect the variables, test some commands and so on. I like ipython, because of the tab completion and the availability of bash commands.

This worked well enough for me, but now my programs grew bigger and include many subroutines (in multiple files). The ipython approach doesn't work any more, because it always runs the complete code till the end of foo.py (when it drops into the pylab shell). What I'd like to do instead is, stop execution at a given line in a subroutine (could be in another file) and inspect variables there. I.e. set a break point at which the pylab shell kicks in.

Is the开发者_高级运维re an easy way to adapt my ipython way of working? E.g. stop at a line in bar.py

ipython -pylab --stop-at bar.py:423 foo.py

or, stop at a subroutine name in bar.py

ipython -pylab --stop-at bar.py:subroutine-name foo.py


You can import the pdb module into the code and then add a pdb.set_trace() call where you would like to have the code stop. Ipython will drop into the interactive debugger, and you are free to step though your code as you wish.


You can drop into a IPython debug session by inserting the following code at the desired point:

import sys, IPython
IPython.Shell.IPShell(argv=[])
IPython.Debugger.Pdb(IPython.ipapi.get().options.colors).set_trace(sys._getframe())

Not exactly what you seem to be looking for, but it works quite nicely for me. It also makes it really easy to have complex conditional breakpoints. There are several other methods of starting an IPython debug session from within your source file floating around on the web, but this - in my experience anyway - is the most reliable in terms of loading the correct colours, tab completion working properly etc.

Once the debug session has started you can set further breakpoints using the break command:

ipdb> break test.py:11
Breakpoint 1 at /tmp/test.py:11
ipdb> b my_function
Breakpoint 2 at /tmp/test.py:5

To make it easy to insert, you can set a macro/key combination in your editor. I'm also a Vim user and I have the following keymap in my vimrc:

nmap <C-P><C-D> oimport sys, IPython<CR>IPython.Shell.IPShell(argv=[])<CR>IPython.Debugger.Pdb(IPython.ipapi.get().options.colors).set_trace(sys._getframe())<ESC>:w<CR>

From normal mode, pressing Ctrl-P then Ctrl-D inserts the debug code after the current line with the correct indentation and then saves the file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜