使用ipdb在一个单元格(jupyter或Ipython)中debuggingpython代码

我正在使用firefox的jupyter(或Ipython)笔记本,并希望debugging单元格中的一些python代码。 我正在使用'import ipdb; ipdb.set_trace()'作为一种断点,例如我的单元格有以下代码:

a=4 import ipdb; ipdb.set_trace() b=5 print a print b 

后用Shift + Enter执行后给我这个错误:

 -------------------------------------------------------------------------- MultipleInstanceError Traceback (most recent call last) <ipython-input-1-f2b356251c56> in <module>() 1 a=4 ----> 2 import ipdb; ipdb.set_trace() 3 b=5 4 print a 5 print b /home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__init__.py in <module>() 14 # You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. 15 ---> 16 from ipdb.__main__ import set_trace, post_mortem, pm, run, runcall, runeval, launch_ipdb_on_exception 17 18 pm # please pyflakes /home/nnn/anaconda/lib/python2.7/site-packages/ipdb/__main__.py in <module>() 71 # the instance method will create a new one without loading the config. 72 # ie: if we are in an embed instance we do not want to load the config. ---> 73 ipapp = TerminalIPythonApp.instance() 74 shell = get_ipython() 75 def_colors = shell.colors /home/nnn/anaconda/lib/python2.7/site-packages/traitlets/config/configurable.pyc in instance(cls, *args, **kwargs) 413 raise MultipleInstanceError( 414 'Multiple incompatible subclass instances of ' --> 415 '%s are being created.' % cls.__name__ 416 ) 417 MultipleInstanceError: Multiple incompatible subclass instances of TerminalIPythonApp are being created. 

如果我不使用浏览器中的jupyter笔记本,而是使用jupyter qtconsole,则会出现同样的错误。 这个错误是什么意思,以及如何避免它? 是否可以使用pdbdebugging器的next,continue等命令逐步debugging单元中的代码?

也有这个问题,它似乎与jupyter和ipdb的版本有关。

解决scheme是用这个代替ipdb库的set_trace调用:

 from IPython.core.debugger import Tracer Tracer()() #this one triggers the debugger 

资料来源: http : //devmartin.com/blog/2014/10/trigger-ipdb-within-ipython-notebook/

注释截图: 截图显示了Tracer()()如何引起Jupyter笔记本反应。它在你的代码的Trace()()行中暂停执行,新的“inline”输入接受ipdb命令,如'p'或'n'或'c',如下所示

如果使用Jupyter Notebook,用魔术命令“ %% debug ”开始你的单元格。 然后一个ipdb行将显示在单元格的底部,这将帮助您浏览debugging会话。 以下命令应该让你开始:

n – 执行当前行并转到下一行。

c – 继续执行,直到下一个中​​断点。

确保每次决定debugging时都要重新启动内核,以便所有variables都是新分配的。您可以通过ipdb行检查每个variables的值,您将看到该variables未定义,直到您执行分配值给那个variables。

 %%debug import pdb from pdb import set_trace as bp def function_xyz(): print('before breakpoint') bp() # This is a breakpoint. print('after breakpoint') 

我的Jupyter版本是5.0.0,我的ipython版本是6.1.0。 我在用

 import IPython.core.debugger dbg = IPython.core.debugger.Pdb() dbg.set_trace() 

Tracer被列为已弃用。

更新:

我尝试使用从另一个答案https://stackoverflow.com/a/43086430/8019692下面的方法,但有一个错误:;

MultipleInstanceError: Multiple incompatible subclass instances of TerminalIPythonApp are being created.

我更喜欢我的方法%%debugging魔术,因为我可以在其他单元格中定义的函数中设置断点,并在另一个单元格中运行该函数。 Jupyter / IPython在设置断点的函数中放入debugging器,我可以使用通常的pdb命令。 对于他自己…

@ lugger1,接受的答案已被弃用。