如何在Visual Studio Code中对Python脚本的单个片段进行执行与调试?
Absolutely! You've got a few solid options to replicate Jupyter Notebook's cell-based workflow in regular .py files within VS Code—no need to switch file types. Here's how to do it:
1. Use Python Interactive Window with Cell Markers
This is the closest you'll get to Jupyter's cell experience, and it's built into VS Code's Python tooling (with the Jupyter extension installed):
- Add
# %%at the start of any code block you want to treat as a "cell". VS Code will automatically recognize this and show a Run Cell button next to the line. - Clicking "Run Cell" executes that block in an interactive window, where variables persist across cell runs—just like in a notebook.
- For debugging: Set breakpoints within the cell, then click the Debug Cell button (it appears next to "Run Cell" when you hover) to step through the code line by line.
2. Run/Debug Selected Code Snippets
If you don't want to add cell markers, you can work directly with arbitrary code sections:
- Highlight the code block you want to execute, then right-click and select
Run Selection/Line in Python Terminal—this runs only the selected code in the integrated terminal. - For debugging highlighted code: Right-click the selection and choose
Debug Selection. VS Code will launch a debug session focused solely on that snippet, letting you set breakpoints, inspect variables, and step through execution.
3. Enable Persistent Interactive Sessions
Once you run a cell or selected code, the interactive window (or terminal) maintains your session state. You can:
- Type additional code directly into the interactive window to test quick ideas.
- Use the "Restart Kernel" button in the interactive window to reset all variables if you need a fresh start.
A quick note: Make sure you have the Jupyter extension installed in VS Code (it's part of the recommended Python extension pack) — most of these cell-based features rely on it.
Hope these methods give you the flexibility you need while keeping your code in .py files! 🚀
内容的提问来源于stack exchange,提问作者banana_99

