在iPython笔记本中调试的正确方法是什么?

时间:2015-09-05 04:53:44

标签: python python-2.7 jupyter-notebook ipython pdb

据我所知,%debug magic可以在一个单元格内进行调试。

但是,我有多个单元格的函数调用。

例如,

In[1]: def fun1(a)
           def fun2(b)
               # I want to set a breakpoint for the following line #
               return do_some_thing_about(b)

       return fun2(a)

In[2]: import multiprocessing as mp
       pool=mp.Pool(processes=2)
       results=pool.map(fun1, 1.0)
       pool.close()
       pool.join

我尝试了什么:

  1. 我尝试在cell-1的第一行设置%debug。但它甚至在执行cell-2之前立即进入调试模式。

  2. 我尝试在代码%debug之前的行中添加return do_some_thing_about(b)。但随后代码永远运行,永不停止。

  3. 在ipython笔记本中设置断点的正确方法是什么?

10 个答案:

答案 0 :(得分:84)

您可以在jupyter中使用ipdb

from IPython.core.debugger import Tracer; Tracer()()

编辑:自IPython 5.1以来,不推荐使用上述功能。这是新方法:

from IPython.core.debugger import set_trace

在需要断点的地方添加set_trace()。输入字段出现时,为help命令键入ipdb

答案 1 :(得分:58)

使用 ipdb

通过

安装
pip install ipdb

用法:

In[1]: def fun1(a):
   def fun2(a):
       import ipdb; ipdb.set_trace() # debugging starts here
       return do_some_thing_about(b)
   return fun2(a)
In[2]: fun1(1)

要逐行执行 n 并使用 s 进入函数并退出调试提示,请使用 c

有关可用命令的完整列表:https://appletree.or.kr/quick_reference_cards/Python/Python%20Debugger%20Cheatsheet.pdf

答案 2 :(得分:12)

你的返回功能符合def功能(主功能),你必须给它一个标签。 并使用

%%debug 

而不是

%debug 

调试整个单元格不仅仅是行。希望,也许这会对你有帮助。

答案 3 :(得分:9)

您可以随时在任何单元格中添加:

import pdb; pdb.set_trace()

并且调试器将在该行停止。例如:

In[1]: def fun1(a):
           def fun2(a):
               import pdb; pdb.set_trace() # debugging starts here
           return fun2(a)

In[2]: fun1(1)

答案 4 :(得分:7)

只需在jupyter笔记本中键入import pdb,然后使用此cheatsheet进行调试。这很方便。

c - >继续,s - >步骤,b 12 - >在第12行设置断点,依此类推。

  

一些有用的链接:   Python Official Document on pdbPython pdb debugger examples for better understanding how to use the debugger commands

     

一些有用的截图:   enter image description here enter image description here

答案 5 :(得分:4)

%pdb magic command也很好用。只需说出%pdb on,随后pdb调试器将在所有异常上运行,无论调用堆栈有多深。非常方便。

如果你想要调试一个特定的行,只需在那里引发异常(通常你已经是!)或使用其他人建议的%debug魔术命令。

答案 6 :(得分:4)

在Python 3.7中,您可以使用breakpoint()函数。只需输入

breakpoint()

无论您希望运行时停止在哪里,都可以使用相同的pdb命令(r,c,n,...)或评估变量。

答案 7 :(得分:3)

出现错误后,在下一个单元格中运行%debug即可。

答案 8 :(得分:3)

我刚刚发现了PixieDebugger。甚至以为我还没有时间对其进行测试,这似乎确实是调试我们在ipdb中使用ipython的方式的最相似方法

enter image description here

它也有一个“评估”标签

答案 9 :(得分:1)

本机调试器已作为JupyterLab的扩展提供。几周前发布,可以通过获取相关扩展以及xeus-python内核(特别是没有ipykernel用户所熟知的魔术来安装)进行安装:

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

这将带来其他IDE众所周知的视觉调试体验。

enter image description here

来源:A visual debugger for Jupyter