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

2024-04-29 12:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

如我所知,%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。但代码永远运行,永不停止。

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


Tags: to代码indebugreturndefmagiccell
3条回答

返回函数在def函数(main函数)的行中,必须给它一个选项卡。 使用

%%debug 

而不是

%debug 

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

您可以在jupyter中使用ipdb与:

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

编辑:自IPython 5.1以来,上述函数已被弃用。这是一种新方法:

from IPython.core.debugger import set_trace

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

使用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

相关问题 更多 >