How to Debug Python Code in Visual Studio Code
Visual Studio Code (VS Code) is a popular editor that offers powerful debugging features for Python. Whether you’re stepping through code, inspecting variables, or diagnosing tricky bugs, VS Code provides all the tools you need for efficient debugging. This tutorial will guide you through setting up and using VS Code’s debugger for Python projects.
Setting Up Python Debugging in VS Code
Step 1: Install VS Code and Python Extension
- Download and install Visual Studio Code.
- Install the Python extension by Microsoft:
- Open the Extensions view (
Ctrl+Shift+X
orCmd+Shift+X
on macOS). - Search for “Python” and click Install.
- Open the Extensions view (
Step 2: Configure Your Python Environment
- Install Python if you haven’t already:
sudo apt install python3 # Linux brew install python3 # macOS winget install Python.Python.3 # Windows
- Set your interpreter in VS Code:
- Open the Command Palette (
Ctrl+Shift+P
orCmd+Shift+P
). - Type Python: Select Interpreter and choose the appropriate environment.
- Open the Command Palette (
Step 3: Create a Debug Configuration
A debug configuration tells VS Code how to run your program during debugging. It defines:
- The Python file to debug (entry point).
- Runtime options like environment variables and arguments.
- Debugging behaviors, such as breakpoints and exception handling.
To create a debug configuration:
- Open your Python project in VS Code.
- Click on the Run and Debug icon (
Ctrl+Shift+D
orCmd+Shift+D
) in the Activity Bar. - Click Create a launch.json file and select Python.
The default configuration for debugging the currently open file will look like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
This setup allows you to debug your Python file directly. You can modify this file later to handle more complex scenarios, such as debugging Django or Flask applications.
Setting Breakpoints
Breakpoints let you pause program execution at specific lines to inspect variables and the flow of your code.
Adding a Breakpoint
- Open a Python file in VS Code.
- Click to the left of a line number, or press
F9
, to set a breakpoint. - A red dot will appear, indicating the breakpoint is active.
Conditional Breakpoints
To pause execution only under specific conditions:
- Right-click the red dot.
- Select Edit Breakpoint Condition.
- Enter a condition like
x > 10
.
Example Code for Debugging
def calculate_area(length, width):
area = length * width
print(f"The area is {area}")
return area
length = 5
width = 10
result = calculate_area(length, width)
Add a breakpoint on the area = length * width
line to pause execution and inspect variables.
Running the Debugger
- Open the Run and Debug view (
Ctrl+Shift+D
orCmd+Shift+D
). - Select Python: Current File in the dropdown menu.
- Click the green play button or press
F5
to start debugging.
Debugging Controls
- Continue (
F5
): Resume execution until the next breakpoint. - Step Over (
F10
): Execute the current line but skip into functions. - Step Into (
F11
): Move into the current function to debug its internals. - Step Out (
Shift+F11
): Exit the current function and return to the caller.
Inspecting Variables and Expressions
Variables Panel
The Variables panel in the Debug Sidebar displays:
- Local Variables: Variables in the current function.
- Global Variables: Variables accessible throughout the program.
Watch Expressions
- In the Debug Sidebar, click + Add Expression under WATCH.
- Enter a variable or expression (e.g.,
length * width
). - The debugger updates the value dynamically as you step through the code.
Debug Console
Use the Debug Console to evaluate expressions interactively:
- Type
area
in the console and press Enter to see its current value. - You can also execute Python code, like
length + width
, to test assumptions.
Advanced Debugging Features
Logging Breakpoints
Instead of pausing execution, logging breakpoints print a message to the console.
- Right-click a breakpoint.
- Select Edit Logpoint.
- Enter a message like
"Area: {area}"
.
Debugging Multiple Files
If your project has multiple files, you can debug across them by setting breakpoints in different modules.
Remote Debugging
VS Code supports debugging remote Python scripts running on a server or container. Add a remote interpreter to your launch.json
file for remote configurations.
Debugging Django or Flask Applications
VS Code includes built-in configurations for debugging popular frameworks:
- For Django, select Python: Django in the dropdown.
- For Flask, select Python: Flask and set the
FLASK_APP
environment variable.
Tips for Efficient Debugging
- Use Debug Profiles: Create multiple configurations in
launch.json
for different scenarios. - Keep an Eye on Logs: Combine debugging with logging for greater insights.
- Leverage Extensions: Use VS Code extensions like Python Test Explorer for debugging tests.
- Automate Testing: Integrate debugging with Pytest to debug failing test cases directly.
Conclusion
Visual Studio Code simplifies Python debugging with its intuitive interface and robust features. From breakpoints and variable inspection to remote debugging and framework-specific setups, VS Code offers a complete toolkit for diagnosing and fixing bugs efficiently.
Start using VS Code for debugging today and streamline your development workflow!