19

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?

Simd
  • 19,447
  • 42
  • 136
  • 271
  • Does this answer your question? [What is the right way to debug in iPython notebook?](https://stackoverflow.com/questions/32409629/what-is-the-right-way-to-debug-in-ipython-notebook) – fuglede Apr 09 '20 at 13:27

5 Answers5

34

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.

nekketsuuu
  • 1,641
  • 1
  • 21
  • 26
14

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

abrac
  • 521
  • 5
  • 12
11

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.

piccolo
  • 2,093
  • 3
  • 24
  • 56
  • 3
    I simply use 0/0 which throws a ZeroDivisionError and stops the execution – Akronix May 17 '20 at 08:31
  • @Akronix that would be simple to use, but confusing for anyone who may look into your code, his answer is descriptive – 27px Aug 05 '22 at 09:12
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.
Zeh
  • 301
  • 2
  • 4
-7

You can probably try exit() but I am not sure if that's exactly what you need.

Drexpp
  • 28
  • 1
  • 6
  • 1
    That 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. – Simd Jun 27 '18 at 20:20