Hướng dẫn vscode debug python
The Python extension supports debugging of 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. Show
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. Initialize configurationsA configuration drives VS Code's behavior during a debugging session. Configurations are defined in a
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
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 configurationsBy default, VS Code shows only the
most common configurations provided by the Python extension. You can select other configurations to include in 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 Basic debuggingIf 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 Debug Python File in Terminal. If you're looking to debug a web application using Flask, Django or FastAPI, the Python 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. Command line debuggingThe debugger can also be run from the command line. The debugger command line syntax is as follows:
As an 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
You would then use the following configuration to attach from the VS Code Python extension.
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.
The associated configuration file would then look as follows.
Debugging by attaching over a network connectionLocal script debuggingThere 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:
Remote script debugging with SSHRemote 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.
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:
On the local computer:
Starting debugging Now that an SSH tunnel has been set up to the remote computer, you can begin your debugging.
Set configuration optionsWhen you first create
The specific settings are described in the following sections. You can also add other settings, such as
|
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: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"autoReload": {
"enable": true
}
}
*Note: When the debugger performs a reload, code that runs on import might be executed again. To avoid this situation, try to only use imports, constants, and definitions in your module, placing all code into functions. Alternatively, you can also use
if __name__=="__main__"
checks.
subProcess
Specifies whether to enable subprocess
debugging. Defaults to false
, set to true
to enable. For more information, see multi-target debugging.
cwd
Specifies the current working directory for the debugger, which is the base folder for any relative paths used in code. If omitted, defaults to ${workspaceFolder}
(the folder open in VS Code).
As an example, say ${workspaceFolder}
contains a
py_code
folder containing app.py
, and a data
folder containing salaries.csv
. If you start the debugger on py_code/app.py
, then the relative paths to the data file vary depending on the value of cwd
:
cwd | Relative path to data file |
---|---|
Omitted or ${workspaceFolder}
| data/salaries.csv
|
${workspaceFolder}/py_code
| ../data/salaries.csv
|
${workspaceFolder}/data
| salaries.csv
|
redirectOutput
When set to true
(the default for internalConsole), causes the debugger to print all output from the program into the VS Code debug output window. If set to false
(the default for integratedTerminal and externalTerminal), program output is not displayed in the debugger output window.
This option is typically disabled when using "console": "integratedTerminal"
or "console": "externalTerminal"
because there's no need to duplicate
the output in the debug console.
justMyCode
When omitted or set to true
(the default), restricts debugging to user-written code only. Set to false
to also enable debugging of standard library functions.
django
When set to true
, activates debugging features specific to the Django web framework.
sudo
When set to true
and
used with "console": "externalTerminal"
, allows for debugging apps that require elevation. Using an external console is necessary to capture the password.
pyramid
When set to true
, ensures that a Pyramid app is launched with the necessary pserve
command.
env
Sets optional environment variables for the debugger process beyond system environment variables, which the debugger always inherits. The values for these variables must be entered as strings.
envFile
Optional path to a file that contains environment variable definitions. See Configuring Python environments - environment variable definitions file.
gevent
If set to true
, enables debugging of gevent monkey-patched code.
jinja
When set to true
, activates debugging features specific to the Jinja templating framework.
Breakpoints and logpoints
The Python extension supports breakpoints and logpoints for debugging code. For a short walkthrough of basic debugging and using breakpoints, see Tutorial - Configure and run the debugger.
Conditional breakpoints
Breakpoints can also be set to trigger based on expressions, hit counts, or a combination of both. The Python extension supports hit counts that are integers, in addition to integers preceded by the ==, >, >=, <, <=,
and % operators. For example, you could set a breakpoint to trigger after five occurrences by setting a hit count of >5
For more information, see conditional breakpoints in the main VS Code debugging article.
Invoking a breakpoint in code
In your Python code, you can call debugpy.breakpoint()
at any
point where you want to pause the debugger during a debugging session.
Breakpoint validation
The Python extension automatically detects breakpoints that are set on non-executable lines, such as pass
statements or the middle of a multiline statement. In such cases, running the debugger moves the breakpoint to the nearest valid line to ensure that code execution stops at that point.
Debugging specific app types
The configuration dropdown provides various different options for general app types:
Configuration | Description |
---|---|
Attach | See Remote debugging in the previous section. |
Django | Specifies "program": "${workspaceFolder}/manage.py" , "args": ["runserver"] . Also adds "django": true to enable debugging of Django HTML templates.
|
Flask | See Flask debugging below. |
Gevent | Adds "gevent": true to the standard integrated terminal configuration.
|
Pyramid | Removes program , adds "args": ["${workspaceFolder}/development.ini"] , adds "jinja": true for enabling template debugging, and adds "pyramid": true to ensure that the program is launched with the necessary pserve command.
|
Scrapy | Specifies "module": "scrapy" and adds "args": ["crawl", "specs", "-o", "bikes.json"] .
|
Watson | Specifies "program": "${workspaceFolder}/console.py" and "args": ["dev", "runserver", "--noreload=True"] .
|
Specific steps are also needed for remote debugging and Google App Engine. For details on debugging tests, see Testing.
To debug an app that requires administrator privileges, use "console": "externalTerminal"
and "sudo": "True"
.
Flask debugging
{
"name": "Python: Flask",
"type": "python",
"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:
{
"name": "Python: Flask (development mode)",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "app.py",
"FLASK_ENV": "development"
},
"args": [
"run"
],
"jinja": true
},
Troubleshooting
There are many reasons why the debugger may not work. Sometimes the debug console reveals specific causes, but the main reasons are as follows:
The path to the python executable is incorrect: check the path of your selected interpreter by running the Python: Select Interpreter command and looking at the current value:
There are invalid expressions in the watch window: clear all expressions from the Watch window and restart the debugger.
If you're working with a multi-threaded app that uses native thread APIs (such as the Win32
CreateThread
function rather than the Python threading APIs), it's presently necessary to include the following source code at the top of whichever file you want to debug:import debugpy debugpy.debug_this_thread()
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:
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
Next steps
- Python environments - Control which Python interpreter is used for editing and debugging.
- Testing - Configure test environments and discover, run, and debug tests.
- Settings reference - Explore the full range of Python-related settings in VS Code.
- General debugging - Learn about the debugging features of VS Code.
7/13/2022