← 返回首页
Python debugging in VS Code

Documentation

Topics Overview Overview Linux macOS Windows VS Code for the Web Raspberry Pi Network Additional Components Uninstall VS Code Tutorial Copilot Quickstart User Interface Personalize VS Code Install Extensions Tips and Tricks Intro Videos Overview Setup Quickstart Overview Language Models Context Tools Agents Customization Trust & Safety Overview Agents Tutorial Agents Window Planning Memory Tools Subagents Local Agents Copilot CLI Cloud Agents Third-Party Agents Overview Chat Sessions Add Context Inline Chat Review Edits Checkpoints Artifacts Panel Debug Chat Interactions Prompt Examples Overview Instructions Prompt Files Custom Agents Agent Skills Language Models MCP Hooks Plugins Context Engineering Customize AI Test-Driven Development Edit Notebooks with AI Test with AI Test Web Apps with Browser Tools Debug with AI MCP Dev Guide OpenTelemetry Monitoring Inline Suggestions Smart Actions Best Practices Security Troubleshooting FAQ Cheat Sheet Settings Reference MCP Configuration Workspace Context Display Language Layout Keyboard Shortcuts Settings Settings Sync Extension Marketplace Extension Runtime Security Themes Profiles Overview Voice Interactions Command Line Interface Telemetry Basic Editing IntelliSense Code Navigation Refactoring Snippets Overview Multi-Root Workspaces Workspace Trust Tasks Debugging Debug Configuration Testing Port Forwarding Integrated Browser Overview Quickstart Staging & Committing Branches & Worktrees Repositories & Remotes Merge Conflicts Collaborate on GitHub Troubleshooting FAQ Getting Started Tutorial Terminal Basics Terminal Profiles Shell Integration Appearance Advanced Overview Enterprise Policies AI Settings Extensions Telemetry Updates Overview JavaScript JSON HTML Emmet CSS, SCSS and Less TypeScript Markdown PowerShell C++ Java PHP Python Julia R Ruby Rust Go T-SQL C# .NET Swift Working with JavaScript Node.js Tutorial Node.js Debugging Deploy Node.js Apps Browser Debugging Angular Tutorial React Tutorial Vue Tutorial Debugging Recipes Performance Profiling Extensions Tutorial Transpiling Editing Refactoring Debugging Quick Start Tutorial Run Python Code Editing Linting Formatting Debugging Environments Testing Python Interactive Django Tutorial FastAPI Tutorial Flask Tutorial Create Containers Deploy Python Apps Python in the Web Settings Reference Getting Started Navigate and Edit Refactoring Formatting and Linting Project Management Build Tools Run and Debug Testing Spring Boot Modernizing Java Apps Application Servers Deploy Java Apps GUI Applications Extensions FAQ Intro Videos GCC on Linux GCC on Windows GCC on Windows Subsystem for Linux Clang on macOS Microsoft C++ on Windows Build with CMake CMake Tools on Linux CMake Quick Start C++ Dev Tools for Copilot Editing and Navigating Debugging Configure Debugging Refactoring Settings Reference Configure IntelliSense Configure IntelliSense for Cross-Compiling FAQ Intro Videos Get Started Navigate and Edit IntelliCode Refactoring Formatting and Linting Project Management Build Tools Package Management Run and Debug Testing FAQ Overview Node.js Python ASP.NET Core Debug Docker Compose Registries Deploy to Azure Choose a Dev Environment Customize Develop with Kubernetes Tips and Tricks Overview Jupyter Notebooks Data Science Tutorial Python Interactive Data Wrangler Quick Start Data Wrangler PyTorch Support Azure Machine Learning Manage Jupyter Kernels Jupyter Notebooks on the Web Data Science in Microsoft Fabric Foundry Toolkit Overview Foundry Toolkit Copilot Tools Create Agents Models Playground Agent Builder Agent Inspector Evaluation Tool Catalog Fine-Tuning (Automated Setup) Fine-Tuning (Project Template) Model Conversion Tracing Profiling (Windows ML) FAQ File Structure Manual Model Conversion Manual Model Conversion on GPU Setup Environment Without Foundry Toolkit Template Project Migrating from Visualizer to Agent Inspector Overview Getting Started Resources View Deployment VS Code for the Web - Azure Containers Azure Kubernetes Service Kubernetes MongoDB Remote Debugging for Node.js Overview SSH Dev Containers Windows Subsystem for Linux GitHub Codespaces VS Code Server Tunnels SSH Tutorial WSL Tutorial Tips and Tricks FAQ Overview Tutorial Attach to Container Create Dev Container Advanced Containers devcontainer.json Dev Container CLI Tips and Tricks FAQ Default Keyboard Shortcuts Default Settings Substitution Variables Tasks Schema
Copy as Markdown

On this page there are 11 sections

Python debugging in VS Code

The Python extension supports debugging through the Python Debugger extension for several types of Python applications. For a short walkthrough of basic debugging, see Tutorial - Configure and run the debugger. Also see the Flask tutorial. Both tutorials demonstrate core skills like setting breakpoints and stepping through code.

For general debugging features such as inspecting variables, setting breakpoints, and other activities that aren't language-dependent, review VS Code debugging.

This article mainly addresses Python-specific debugging configurations, including the necessary steps for specific app types and remote debugging.

Python Debugger Extension

The Python Debugger extension is automatically installed along with the Python extension for VS Code. It offers debugging features with debugpy for several types of Python applications, including scripts, web apps, remote processes and more.

To verify it's installed, open the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)) and search for @installed python debugger. You should see the Python Debugger extension listed in the results.

You can refer to the extension's README page for information on supported Python versions.

Initialize configurations

A configuration drives VS Code's behavior during a debugging session. Configurations are defined in a launch.json file that's stored in a .vscode folder in your workspace.

Note: To change debugging configuration, your code must be stored in a folder.

To initialize debug configurations, first select the Run view in the sidebar:

If you don't yet have any configurations defined, you'll see a button to Run and Debug and a link to create a configuration (launch.json) file:

To generate a launch.json file with Python configurations, do the following steps:

  1. Select the create a launch.json file link (outlined in the image above) or use the Run > Open configurations menu command.

  2. Select Python Debugger from the debugger options list.

  3. A configuration menu will open from the Command Palette allowing you to choose the type of debug configuration you want to use for our Python project file. If you want to debug a single Python script, select Python File in the Select a debug configuration menu that appears.

    Note: Starting a debugging session through the Debug Panel, F5, or Run > Start Debugging when no configuration exists will also bring up the debug configuration menu, but will not create a launch.json file.

  4. The Python Debugger extension then creates and opens a launch.json file that contains a pre-defined configuration based on what you previously selected, in this case, Python File. You can modify configurations (to add arguments, for example), and also add custom configurations.

The details of configuration properties are covered later in this article under Standard configuration and options. Other configurations are also described in this article under Debugging specific app types.

Additional configurations

By default, VS Code shows only the most common configurations provided by the Python Debugger extension. You can select other configurations to include in launch.json by using the Add Configuration command shown in the list and the launch.json editor. When you use the command, VS Code prompts you with a list of all available configurations (be sure to select the Python option):

Selecting the Attach using Process ID one yields the following result:

See Debugging specific app types for details on all of these configurations.

During debugging, the Status Bar shows the current configuration and the current debugging interpreter. Selecting the configuration brings up a list from which you can choose a different configuration:

By default, the debugger uses the same interpreter selected for your workspace, just like other features of Python extension for VS Code. To use a different interpreter for debugging specifically, set the value for python in launch.json for the applicable debugger configuration. Alternately, use the Python interpreter indicator on the Status Bar to select a different one.

Basic debugging

If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Python Debugger: Debug Python File.

If you're looking to debug a web application using Flask, Django or FastAPI, the Python Debugger extension provides dynamically created debug configurations based on your project structure under the Show all automatic debug configurations option, through the Run and Debug view.

But if you're looking to debug other kinds of applications, you can start the debugger through the Run view by clicking on the Run and Debug button.

When no configuration has been set, you'll be given a list of debugging options. Here, you can select the appropriate option to quickly debug your code.

Two common options are to use the Python File configuration to run the currently open Python file or to use the Attach using Process ID configuration to attach the debugger to a process that is already running.

For information about creating and using debugging configurations, see the Initialize configurations and Additional configurations sections. Once a configuration is added, it can be selected from the dropdown list and started using the Start Debugging button (F5).

Command line debugging

The debugger can also be run from the command line, if debugpy is installed in your Python environment.

Install debugpy

You can install debugpy using python -m pip install --upgrade debugpy into your Python environment.

Tip

While using a virtual environment is not required, it is a recommended best practice. You can create a virtual environment in VS Code by opening the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and running the Python: Create Environment command, or by selecting the + button in the Environment Managers view.

Command line syntax

The debugger command line syntax is as follows:

python -m debugpy --listen 5678 ./myscript.py

You would then use the following configuration to attach from the VS Code Python Debugger extension.

python -m debugpy --listen 0.0.0.0:5678 ./myscript.py

The associated configuration file would then look as follows.

import debugpy # 5678 is the default attach port in the VS Code debug configurations. Unless a host and port are specified, host defaults to 127.0.0.1 debugpy.listen(5678) print("Waiting for debugger attach") debugpy.wait_for_client() debugpy.breakpoint() print('break on this line')
  • Open a terminal using Terminal: Create New Terminal, which activates the script's selected environment.

  • In the terminal, install the debugpy package.

  • In the terminal, start Python with the script, for example, python3 myscript.py. You should see the "Waiting for debugger attach" message that's included in the code, and the script halts at the debugpy.wait_for_client() call.

  • Switch to the Run and Debug view (⇧⌘D (Windows, Linux Ctrl+Shift+D)), select the appropriate configuration from the debugger dropdown list, and start the debugger.

  • The debugger should stop on the debugpy.breakpoint() call, from which point you can use the debugger normally. You also have the option of setting other breakpoints in the script code using the UI instead of using debugpy.breakpoint().

  • Remote script debugging with SSH

    Remote debugging allows you to step through a program locally within VS Code while it runs on a remote computer. It is not necessary to install VS Code on the remote computer. For added security, you may want or need to use a secure connection, such as SSH, to the remote computer when debugging.

    Note: On Windows computers, you may need to install Windows 10 OpenSSH to have the ssh command.

    The following steps outline the general process to set up an SSH tunnel. An SSH tunnel allows you to work on your local machine as if you were working directly on the remote in a more secure manner than if a port was opened for public access.

    On the remote computer:

    1. Enable port forwarding by opening the sshd_config config file (found under /etc/ssh/ on Linux and under %programfiles(x86)%/openssh/etc on Windows) and adding or modifying the following setting:

      { "name": "Python Debugger: Attach", "type": "debugpy", "request": "attach", "port": 5678, "host": "localhost", "pathMappings": [ { "localRoot": "${workspaceFolder}", // Maps C:\Users\user1\project1 "remoteRoot": "." // To current working directory ~/project1 } ] }

    Starting debugging

    Now that an SSH tunnel has been set up to the remote computer, you can begin your debugging.

    1. Both computers: make sure that identical source code is available.

    2. Both computers: install debugpy.

    3. Remote computer: there are two ways to specify how to attach to the remote process.

      1. In the source code, add the following lines, replacing address with the remote computer's IP address and port number (IP address 1.2.3.4 is shown here for illustration only).

        python3 -m debugpy --listen 1.2.3.4:5678 --wait-for-client -m myproject

        This starts the package myproject using python3, with the remote computer's private IP address of 1.2.3.4 and listening on port 5678 (you can also start the remote Python process by specifying a file path instead of using -m, such as ./hello.py).

    4. Local computer: Only if you modified the source code on the remote computer as outlined above, then in the source code, add a commented-out copy of the same code added on the remote computer. Adding these lines makes sure that the source code on both computers matches line by line.

      { "configurations": [ { "name": "Python Debugger: Current File (Integrated Terminal)", "type": "debugpy", "request": "launch", "program": "${file}", "console": "integratedTerminal" }, { "name": "Python Debugger: Current File (External Terminal)", "type": "debugpy", "request": "launch", "program": "${file}", "console": "externalTerminal" } ] }

      The specific settings are described in the following sections. You can also add other settings, such as args, that aren't included in the standard configurations.

      Tip: It's often helpful in a project to create a configuration that runs a specific startup file. For example, if you want to always launch startup.py with the arguments --port 1593 when you start the debugger, create a configuration entry as follows:

      "program": "/Users/Me/Projects/MyProject/src/event_handlers/__init__.py",

      You can also rely on a relative path from the workspace root. For example, if the root is /Users/Me/Projects/MyProject then you can use the following example:

      "args": ["--quiet", "--norepeat", "--port", "1593"],

      If you want to provide different arguments per debug run, you can set args to "${command:pickArgs}". This will prompt you to enter arguments each time you start a debug session.

      Note: There is a difference in how "${command:pickArgs}" and ["${command:pickArgs}"] are parsed, with specific notice to the usage of []. As an array, all arguments are passed as a single string, without brackets each argument is passed as its own string.

      stopOnEntry

      When set to true, breaks the debugger at the first line of the program being debugged. If omitted (the default) or set to false, the debugger runs the program to the first breakpoint.

      console

      Specifies how program output is displayed as long as the defaults for redirectOutput aren't modified.

      Value Where output is displayed
      "internalConsole" VS Code debug console. If redirectOutput is set to False, no output is displayed.
      "integratedTerminal" (default) VS Code Integrated Terminal. If redirectOutput is set to True, output is also displayed in the debug console.
      "externalTerminal" Separate console window. If redirectOutput is set to True, output is also displayed in the debug console.

      purpose

      There is more than one way to configure the Run button, using the purpose option. Setting the option to debug-test, defines that the configuration should be used when debugging tests in VS Code. However, setting the option to debug-in-terminal, defines that the configuration should only be used when accessing the Run Python File button on the top-right of the editor (regardless of whether the Run Python File or Debug Python File options the button provides is used). Note: The purpose option can't be used to start the debugger through F5 or Run > Start Debugging.

      autoReload

      Allows for the automatic reload of the debugger when changes are made to code after the debugger execution has hit a breakpoint. To enable this feature set {"enable": true} as shown in the following code.

      { "name": "Python Debugger: Flask", "type": "debugpy", "request": "launch", "module": "flask", "env": { "FLASK_APP": "app.py" }, "args": [ "run", "--no-debugger" ], "jinja": true },

      As you can see, this configuration specifies "env": {"FLASK_APP": "app.py"} and "args": ["run", "--no-debugger"]. The "module": "flask" property is used instead of program. (You may see "FLASK_APP": "${workspaceFolder}/app.py" in the env property, in which case modify the configuration to refer to only the filename. Otherwise, you may see "Cannot import module C" errors where C is a drive letter.)

      The "jinja": true setting also enables debugging for Flask's default Jinja templating engine.

      If you want to run Flask's development server in development mode, use the following configuration:

      import debugpy debugpy.debug_this_thread()
    5. If you are working with a Linux system, you may receive a "timed out" error message when trying to apply a debugger to any running process. To prevent this, you can temporarily run the following command: