How to add a breakpoint in Jupyter notebook?
Solution 1
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.
Solution 2
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:
You can then debug your code as follows:
Source: https://jupyterlab.readthedocs.io/en/stable/user/debugger.html
Solution 3
As far as I know, jupyter notebook doesn't have a breakpoint function however you can add something like:
assert False, "breakpoint"
where you want to stop although it isn't very elegant.
Solution 4
- Ensure that you have selected the kernel (e.g., Python 3) on the upper right corner of the coding window
- Select the debugging icon on its left (as you select it, each line will be numbered)
- Now you can select breakpoints, by clicking on the line number.
graffe
Updated on June 13, 2022Comments
-
graffe almost 2 years
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 alsoGood 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?
-
graffe almost 6 yearsThat does exactly the same as using
quit()
as far as I can tell. In other words it doesn't stop the rest of the script from running. -
Akronix almost 4 yearsI simply use 0/0 which throws a ZeroDivisionError and stops the execution
-
graffe about 3 yearsThis looks exciting!
-
Prashant Saraswat about 2 yearsNote for self, instead of running jupyter notebook, run jupyter-lab. this is a different interface and allows debugging. The old one does not.
-
David H. J. almost 2 yearsGreat news. Any recommended kernal for Conda?
-
David H. J. almost 2 yearsAny recommended kernal for Conda?
-
abrac almost 2 yearsI think
xeus-python
is also available in Conda. Try:conda install -c conda-forge xeus-python
-
pabouk - Ukraine stay strong almost 2 yearsNow you do not need any special kernel but you have to enable the debugger using the bug icon (on the right side of the notebook's top bar). I am using the debugger in JupyterLab 3.4, Python 3.10.