Search code examples
pythonpython-3.xvisual-studio-codevscode-debugger

How can I use the Python debugger (with breakpoints) while using the interactive mode in VS Code?


Here is a simplified example to show the problem I have in VS Code:

#%% cell 1
import time

def myfunc():
    a = 5  # <-- Put breakpoint here
    b = 0
    return a/b

#%% cell 2
t = time.time()
print("started at", t)
myfunc()

I put a breakpoint at a = 5 then I press SHIFT+ENTER twice to execute both cells. The interactive window shows the print, but then show the exception: ZeroDivisionError: division by zero instead of activating my breakpoint.

How can I activate the debugger without losing the current variables (like t) from the interactive session?

I want to make it stop at the breakpoint the next time I press SHIFT+ENTER and be able to step through myfunc.

EDIT:

As @MingJie-MSFT pointed out, I can use CTRL+SHIFT+P > Jupyter: Debug Current Cell command to enable the debugger.

Is it normal that when I invoke this command, I immediately see line 3445 of interactiveshell.py, instead of breaking into my code? Internal debugger code


Solution

  • I press SHIFT+ENTER twice to execute both cells.

    SHIFT+ENTER means run current cell instead of debug the cell.

    enter image description here

    You can click Debug Cell to achieve it.

    enter image description here

    Read document for more details.

    You can also use jupyter notebook. It's the same as interactive window.

    enter image description here