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 (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:
-
Select the create a launch.json file link (outlined in the image above) or use the Run > Open configurations menu command.
-
Select Python Debugger from the debugger options list.
-
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 alaunch.json
file. -
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 (
Ctrl+Shift+P
) and running the Python: Create Virtual Environment command (kb(workbench.action.terminal.newWithProfilePython)
).
Command line syntax
The debugger command line syntax is as follows:
python -m debugpy
--listen | --connect
[<host>:]<port>
[--wait-for-client]
[--configure-<name> <value>]...
[--log-to <path>] [--log-to-stderr]
<filename> | -m <module> | -c <code> | --pid <pid>
[<arg>]...
Example
From the command line, you could start the debugger using a specified port (5678) and script using the following syntax. This example assumes the script is long-running and omits the --wait-for-client
flag, meaning that the script will not wait for the client to attach.
python -m debugpy --listen 5678 ./myscript.py
You would then use the following configuration to attach from the VS Code Python Debugger extension.
{
"name": "Python Debugger: Attach",
"type": "debugpy",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
}
}
Note: Specifying host is optional for listen, by default 127.0.0.1 is used.
If you wanted to debug remote code or code running in a docker container, on the remote machine or container, you would need to modify the previous CLI command to specify a host.
python -m debugpy --listen 0.0.0.0:5678 ./myscript.py
The associated configuration file would then look as follows.
{
"name": "Attach",
"type": "debugpy",
"request": "attach",
"connect": {
"host": "remote-machine-name", // replace this with remote machine name
"port": 5678
}
}
Note: Be aware that when you specify a host value other than
127.0.0.1
orlocalhost
you are opening a port to allow access from any machine, which carries security risks. You should make sure that you're taking appropriate security precautions, such as using SSH tunnels, when doing remote debugging.
Command line options
Flag | Options | Description |
---|---|---|
--listen or --connect | [<host>:]<port> | Required. Specifies the host address and port for the debug adapter server to wait for incoming connections (--listen) or to connect with a client that is waiting for an incoming connection (--connect). This is the same address that is used in the VS Code debug configuration. By default, the host address is localhost (127.0.0.1) . |
--wait-for-client | none | Optional. Specifies that the code should not run until there's a connection from the debug server. This setting allows you to debug from the first line of your code. |
--log-to | <path> | Optional. Specifies a path to an existing directory for saving logs. |
--log-to-stderr | none | Optional. Enables debugpy to write logs directly to stderr. |
--pid | <pid> | Optional. Specifies a process that is already running to inject the debug server into. |
--configure-<name> | <value> | Optional. Sets a debug property that must be known to the debug server before the client connects. Such properties can be used directly in launch configuration, but must be set in this manner for attach configurations. For example, if you don't want the debug server to automatically inject itself into subprocesses created by the process you're attaching to, use --configure-subProcess false . |
Note:
[<arg>]
can be used to pass command-line arguments along to the app being launched.
Debugging by attaching over a network connection
Local script debugging
There may be instances where you need to debug a Python script that's invoked locally by another process. For example, you may be debugging a web server that runs different Python scripts for specific processing jobs. In such cases, you need to attach the VS Code debugger to the script once it's been launched:
-
Run VS Code, open the folder or workspace containing the script, and create a
launch.json
for that workspace if one doesn't exist already. -
In the script code, add the following and save the file:
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 thedebugpy.wait_for_client()
call. -
Switch to the Run and Debug view (
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 usingdebugpy.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:
-
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:AllowTcpForwarding yes
Note: The default for AllowTcpForwarding is yes, so you might not need to make a change.
-
If you had to add or modify
AllowTcpForwarding
, restart the SSH server. On Linux/macOS, runsudo service ssh restart
; on Windows, runservices.msc
, select OpenSSH orsshd
in the list of services, and select Restart.
On the local computer:
-
Create an SSH tunnel by running
ssh -2 -L sourceport:localhost:destinationport -i identityfile user@remoteaddress
, using a selected port fordestinationport
and the appropriate username and the remote computer's IP address inuser@remoteaddress
. For example, to use port 5678 on IP address 1.2.3.4, the command would bessh -2 -L 5678:localhost:5678 -i identityfile [email protected]
. You can specify the path to an identity file, using the-i
flag. -
Verify that you can see a prompt in the SSH session.
-
In your VS Code workspace, create a configuration for remote debugging in your
launch.json
file, setting the port to match the port used in thessh
command and the host tolocalhost
. You uselocalhost
here because you've set up the SSH tunnel.{
"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
}
]
}