using ipdb to debug python code in one cell (jupyter or Ipython)

岁酱吖の 提交于 2019-11-28 15:25:26
Robert Muil

Had this problem also and it seems to be related to versions of jupyter and ipdb.

Solution is to use this instead of the ipdb library set_trace call:

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

Source: http://devmartin.com/blog/2014/10/trigger-ipdb-within-ipython-notebook/

Annotated screenshot:

If using Jupyter Notebook begin your cell with magic command "%%debug". Then a ipdb line will be shown at the bottom of the cell which will help you navigate through the debugging session. Following commands should get you started:

n- execute current line and go to next line.

c- continue execution until next break point.

Make sure you restart the kernel each time you decide on debugging, so that all variables are freshly assigned.You can check the value of each variable through the ipdb line and you will see that the variable is undefined until you execute the line that assigns a value to that variable.

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

My version of Jupyter is 5.0.0 and my corresponding ipython version is 6.1.0. I am using

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

Tracer is listed as deprecated.

Update:

I tried using the method from another answer https://stackoverflow.com/a/43086430/8019692 below but got an error:

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

I prefer my method to the %%debug magic since I can set breakpoints in functions defined in other cells and run the function in another cell. Jupyter/IPython drops into the debugger in my function where the breakpoint is set, and I can use the usual pdb commands. To each his own...

@lugger1, the accepted answer is deprecated.

Tracer() is deprecated.

Use:

from IPython.core.debugger import set_trace

and then place set_trace() where breakpoint is needed.

from IPython.core.debugger import set_trace

def add_to_life_universe_everything(x):
    answer = 42
    set_trace()
    answer += x

    return answer

add_to_life_universe_everything(12)

This works fine and brings us a little bit more comfort (e.g. syntax highlighting) than just using the built-in pdb.

source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!