Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a breakpoint in Jupyter notebook?

In Jupyter notebook, if I have

print("hello")
quit()

in the first cell and

print("Good bye")

in the second, when I do "Run all" it prints hello and also Good bye.

In other words, quit() seems to only stop the execution of the cell itself, not the whole script.

Is there some way to add a breakpoint to your code so that it stops executing when it gets to it?

like image 934
graffe Avatar asked Jun 27 '18 18:06

graffe


People also ask

Is there a debug mode in Jupyter notebook?

Debug code in Jupyter notebooks The Jupyter Notebook Debugger tool window opens. Debugging is performed within a single code cell. However, if your code cell calls a function from any cell that has been already debugged, you can step into it. The related breakpoints will also work.

How do you add a breakpoint?

To set a breakpoint in source code, click in the far left margin next to a line of code. You can also select the line and press F9, select Debug > Toggle Breakpoint, or right-click and select Breakpoint > Insert breakpoint. The breakpoint appears as a red dot in the left margin.

How do you do a breakpoint in Python?

Python breakpoint() - Stop Debugging Python sys. breakpointhook() function uses environment variable PYTHONBREAKPOINT to configure the debugger. If unset, the default PDB debugger is used. If it's set to “0” then the function returns immediately and no code debugging is performed.

How do you set a breakpoint within your code?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint.


2 Answers

You can use IPython.core.debugger.Pdb to invoke pdb. Insert the following line to set a breakpoint.

from IPython.core.debugger import Pdb; Pdb().set_trace()

See this page for debugger commands.

Also, you can use %debug magic to invoke pdb after an error. Just type %debug to the next cell if an exception occurs. Then pdb runs from its stack frames.

like image 100
nekketsuuu Avatar answered Oct 17 '22 01:10

nekketsuuu


From the JupyterLab docs:

JupyterLab 3.0 now ships with a Debugger front-end by default.

For the debugger to be enabled and visible, a kernel with support for debugging is required.

If you are using Pip, install the Xeus-Python kernel with pip install xeus-python.

Then open a jupyterlab notebook, and choose the new kernel from the toolbar:

Selecting Kernel

You can then debug your code as follows:

Debugging in JupyterLab

Source: https://jupyterlab.readthedocs.io/en/stable/user/debugger.html

like image 11
abrac Avatar answered Oct 17 '22 02:10

abrac