Debugging Configurations For Python Apps In Visual Studio Code
Có thể bạn quan tâm
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:
-
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 a launch.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 (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and running the Python: Create Virtual Environment command ().
Command line syntax
The debugger command line syntax is as follows:
python -m debugpy --listen 5678 ./myscript.pyYou 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.pyThe 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:
-
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.
-
Both computers: make sure that identical source code is available.
-
Both computers: install debugpy.
-
Remote computer: there are two ways to specify how to attach to the remote process.
-
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 myprojectThis 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).
-
-
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.
"program": "/Users/Me/Projects/MyProject/src/event_handlers/__init__.py",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:
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() -
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:
Từ khóa » Visual Studio Code Run Python Debugger
-
Get Started Tutorial For Python In Visual Studio Code
-
How To Debug Python Scripts In Visual Studio Code - SQLShack
-
How To Debug Python With VSCode - YouTube
-
How To Debug Python In VSCode - Lightrun
-
How To Debug Python Scripts In Visual Studio Code - JT1
-
Debug Python Code - Visual Studio (Windows) - Microsoft Docs
-
How To Make The Most Of Your Python Debugger In VSCode
-
Python In VSCode: Running And Debugging
-
Python Debugging With VS Code
-
Visual Studio Code Can't Debug Python Program - Stack Overflow
-
Visual Studio Code Linux Python Debugger Doesn't Execute
-
Python Debug Configurations In Visual Studio Code - Morioh
-
Setting Up Python Debugger In VSCode | By Amy @GrabNGoInfo
-
15. Debugging With Visual Studio Code