IPython (Jupyter) 笔记本中的交互式调试

Interactive debugging in IPython (Jupyter) notebook

为了调试我的 python 代码,我使用 ipdb 库,并使用 set_trace() 命令放置一个断点。一旦代码到达那里,我就会得到一个带有 ipdb> 提示符的交互式 shell,我可以使用选项卡自动完成来探索局部变量。

但是,在 IPython (Jupyter) notebook 中,ipdb.set_trace() 不起作用。正如这个 post 所建议的:

我使用以下替代方法进行交互式调试:

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

这给了我 ipdb> 提示,但选项卡自动完成不可用。无论如何,是否可以使用 ipython notebook 为交互式调试启用自动完成功能?这非常有用,特别是当您有很多长名称的变量时。

在Python 3.7中你可以使用breakpoint()函数

This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice.