Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to debug Python with VScode code

2025-04-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to debug Python with VScode code. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

The Python extension supports debugging of many types of Python applications, including the following general features:

Viewing window

Evaluation expression

a native

Parameters.

Enlarge the child

Breakpoint

Conditional breakpoint

Pause (enter) a running program

Customize the startup directory

To familiarize yourself with these general features, check out the VS Code debugging article. This article discusses only those considerations that are specific to Python.

Select a configuration

To select a debug configuration, select the debug view in the sidebar, and then select an option from the drop-down list:

When debugging, the status bar displays the current configuration in the lower left corner, and the current debug interpreter is located on the right. Selecting a configuration displays a list from which you can select a different configuration:

By default, the debugger uses the same settings as other features of python.pythonPathVS Code. To use a different interpreter, pythonPath sets this value in the debugger settings. Alternatively, select the specified interpreter on the status bar to select a different interpreter.

Note: debugger settings do not support relative paths, including when relying on the primary python.pythonPath setting. To solve this problem, use an environment variable, or create a variable, such as ${workspaceFolder}, resolve to your project folder, and then use the variable in the path, such as in "python.pythonPath": "${workspaceFolder} / venv/bin/python".

To view all configurations, launch.json opens by selecting the gear icon next to the configuration drop-down list:

The next section describes the default or standard "Python: current file" configuration. This article also describes other configurations for debugging specific application types.

Note: if you want to try a new experimental debugger, see the instructions on Issue 538 (GitHub).

Standard configuration and option

Standard configuration is launch.json:

{"name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}",}

The following sections describe the custom configuration of the various settings.

Name

Provides the name of the debug configuration that appears in the VS Code drop-down list.

Type

Identify the type of debugger to use; leave this setting to the pythonPython code.

Request

Specify the mode in which to start debugging:

Launch: starts the debugger program on the file specified in

Attach: attach the debugger to an already running process. For an example, see remote debugging.

Program

Provides a fully qualified path to the python program entry module. The recommended value is ${file}, which uses the active file in the editor. However, for programs with multiple files, you can specify the startup file for the program. For example:

"program": "/ Users/Me/Projects/PokemonGo-Bot/pokemongo_bot/event_handlers/__init__.py"

You can also rely on the relative path in the root directory of the workspace. For example, if the root is / Users/Me/Projects/PokemonGo-Bot, you can use the following:

"program": "${workspaceFolder} / pokemongo_bot/event_handlers/__init__.py", pythonPath

Point to the Python interpreter for debugging purposes. If not specified, the default is the interpreter identified in the python.pythonPath setting, which is equivalent to using the value ${config:python.pythonPath}. To use a different interpreter, specify its path instead.

You can name the osx,windows or linux in the parent object by specifying the platform-specific path pythonPath. For example, the configuration of PySpark uses the following values:

"osx": {"pythonPath": "^\"\ ${env:SPARK_HOME} / bin/spark-submit\ "}," windows ": {" pythonPath ":" ^\ "\ ${env:SPARK_HOME} / bin/spark-submit.cmd\"}, "linux": {"pythonPath": "^\"\ ${env:SPARK_HOME} / bin/spark-submit\ "}, args

Specify the parameters passed to the Python program, such as:

"args": ["- quiet", "- norepeat"], stopOnEntry

When set to true, disconnect the debugger on the first line of the debugger. If omitted (default) or set to false, the debugger runs the program to the first breakpoint.

Console

Specifies how the program output is displayed.

Value shows the output where "none" VS code debugging console "integratedTerminal" (default) VS code integration terminal "externalTerminal" stand-alone console window cwd

Specifies the current working directory of the debugger, which is the underlying folder for any relative paths used in the code. If omitted, the default is ${workspaceFolder} (the folder opened in the VS code).

As an example, say that ${workspaceFolder} contains a py_code folder containing app.py, and a data folder containing salaries.csv. If you start the debugger py_code/app.py, the relative path to the data file changes cwd based on the following values:

The relative path of the CWD data file is omitted or ${workspaceFolder} data/salaries.csv$ {workspaceFolder} / py_code). / data/salaries.csv$ {workspaceFolder} / datasalaries.csvdebugOptions

A series of additional options that may include:

The option description "RedirectOutput" (default) causes the debugger to print all the output of the program to the VS Code debug output window. If you omit this setting, all program output is not displayed in the debugger output window. This option is usually omitted when used, "console": "integratedTerminal" or "console": "externalTerminal" because there is no need to copy the output in the debug console. "DebugStdLib" enables debugging of standard library functions. "Django" activates debugging features specific to the Django Web framework. "Sudo" and. When used together, "console": "externalTerminal" allows debugging of applications that need to be upgraded. An external console is required to capture passwords. "Pyramid" is used when debugging pyramid applications. Env

Sets optional environment variables for debugger processes other than the system environment variables that the debugger always inherits.

EnvFile

An optional path to the file that contains the definition of the environment variable. See configure the Python environment-environment variable definition file.

Debug specific application types

The configuration drop-down menu provides a variety of options for regular application types:

The configuration description PySpark runs the program using PySpark instead of the default interpreter, using the platform-specific values shown earlier in pythonPath under the pythonPath option. The Python module replaces the program setting "module": "module.name" to debug a specific module. When using this configuration, replace the value with the desired module name. The integrated terminal / console adds the "console": "integratedTerminal" option to the standard configuration. External terminal / console adds the "console": "externalTerminal" option to the standard configuration. Specify "program" for Django: "${workspaceFolder} / manage.py" and "args": ["runserver", "--noreload", "--nothreading"] add "Django" and "RedirectOutput" debugOptions. Note that the Django application cannot be automatically reloaded while debugging. To debug the Django HTML template, add a breakpoint templates. See Flask debugging below for flasks. Remove program from the pyramid, add "args": ["${workspaceFolder} / development.ini"] and add "pyramid" and "redirect output" debugOptions. Watson specifies "program": "${workspaceFolder} / console.py" and "args": ["dev", "runserver", "--noreload=True"] Scrapy specifies "program": "~ / .virtualenvs / scrapy/bin/scrapy", add the "console": "integratedTerminal" option and add "args": ["crawl", "specs", "- o", "bikes.json"]. For additional (remote debugging), see remote debugging below.

Remote debugging and Google App Engine also require specific steps. For more information about debugging unit tests, including nosetest, see Unit Tests.

To debug applications that require administrator privileges, use "console": "externalTerminal" in and include the "Sudo" debugOptions.

"name": "Flask", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "${config:python.pythonPath}", "module": "flask", "cwd": "${workspaceFolder}", "env": {"FLASK_APP": "${workspaceFolder} / app.py"} "args": ["run", "--no-debugger", "--no-reload"]}

As you can see, this configuration specifies "stopOnEntry": false, "env": {"FLASK_APP": "${workspaceFolder} / app.py"} and "args": ["run", "--no-debugger", "--no-reload"]. The "module": "flask" attribute is used instead of program.

Remote debugging

Remote debugging allows you to execute a program locally in your VS code while executing it on a remote computer. In this case, the source code must be available on both computers.

On development and remote computers, install ptvsd 3.0.0 (full version 3.0.0-later versions do not yet support # 514).

In the source code for both computers, add the following line, replace _ my_secret_ with the appropriate password to verify remote debugging, and replace _ address _ localhost with the appropriate IP address (or) and port number:

Import ptvsdptvsd.enable_attach ("my_secret", address = ('0.0.0.0, 3000)) # Enable the line of source code below only if you want the application to wait until the debugger has attached to it#ptvsd.wait_for_attach ()

On the remote computer only, uncomment the last line above. You want to keep comment lines on the development machine to ensure that the source code on both machines matches the lines.

Start the remote program.

Select the additional (remote debugging) (below) configuration, then modify the remoteRoot to point to the location on the remote computer of the program, and modify the value match in the source code added by host,port and secret above.

{"name": "Attach (Remote Debug)", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "${workspaceFolder}", "port": 3000, "secret": "my_secret", "host": "localhost"}

Debug through SSH

Windows:

Use sshd_config or similar commands to enable ssh port forwarding on the remote computer.

Establish a PuTTY SSH tunnel:

Read setting up SSH tunnels using PuTTY (until the "Open session" section).

On the Tunnel screen, using local mode, the source port (the entry point port on the local computer) may be different from the destination port (the endpoint on the server).

The destination address should be the local host or 127.0.0.1 address (this is the address used by the remote SSH server to establish the tunnel).

Linux's:

Run ssh-L sourceport:localhost:destinationport user@remoteaddress

Next, verify that you can see the prompt in the SSH session. Then open VS Code and configure the port as the debug port that appears on the Tunnels screen.

Finally, start the program and attach the debugger as described in the previous section.

Google App Engine debugging

Google App Engine starts an application itself, so it is not directly possible to start it in the VS Code debugger. Instead, we need to use ptvsd in our application and then start Google App Engine in a mode that allows VS Code to attach its debugger.

Download ptvsd and extract its files to the ptvsd folder in the working folder. (if you are using a different folder, modify the path in the file created in step 4 of pydev_startup.py).

Tasks.json creates a file with the following:

{"version": "2.0.0", "tasks": [{"label": "Launch Google App Engine", "command": "python", "type": "shell", "args": ["/ usr/local/google_appengine/dev_appserver.py" "--python_startup_script=$ {workspaceFolder} / pydev_startup.py", "--automatic_restart=no", "--max_module_instances=default:1", "${workspaceFolder} / app.yaml"]}

On Windows and Linux, replace the first item args with the path where you installed Google App Engine (the path shown in the source code above applies to MacOS).

Create a file called pydev_startup.py under the root of your project, which contains the following and follow the instructions:

Import sysimport os#Assuming that pdvsd is located in the working foldersys.path.append (os.getcwd ()) import ptvsd# Modify the secret and port number as desired; you're debugging locally so the values don't matter.# However, be sure the port is not blocked on your computer.ptvsd.enable_attach (secret = 'gae', address = (' 0.0.0.0, 3000)) # The debug server has started and you can now use VS Code to attach to the application for debuggingprint ("Google App Engine has started, ready to attach the debugger")

Launch.json uses the Attach (remote debugging) configuration as a template to create the configuration. Make sure that the secret and port values match the contents of the source code above.

Add "preLaunchTask": "python" to launch.json.

From the command panel, run the run build Task command. This opens the task output window where you can see various messages.

Once you see the message "Google App Engine is started, ready to connect to the debugger", start the VS Code debugger using the remote debugging configuration.

Set a breakpoint where you need it, and then launch the browser to start the application.

Troubleshooting

There are many reasons why the debugger may not work properly. The debugging console often shows specific reasons, but there are two specific reasons:

The path to the python executable is incorrect: please check the value in the pythonPath user settings.

Invalid expressions in the observation window (see example below): clear all expressions in the Watch window and restart the debugger.

Traceback (most recent call last): File "... / visualstudio_py_debugger.py", line 1646, in loop cmd () File "... / visualstudio_py_debugger.py", line 1918, in command_execute_code thread.run_on_thread (text, cur_frame, eid, frame_kind, repr_kind) File "... / visualstudio_py_debugger.py", line 1246, in run_on_thread self.schedule_work (lambda: self.run_locally (text, cur_frame) Execution_id, frame_kind, repr_kind) File "... / visualstudio_py_debugger.py", line 1238, in schedule_work self.unblock () File "... / visualstudio_py_debugger.py", line 1234, in unblock self._block_lock.release () RuntimeError: release unlocked lock

On "how to debug Python with VScode code" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report