How do I debug Python applications in VS Code?
Jul 16, 2025 am 02:47 AMHow to debug a Python application in VS Code? The answer is to configure the environment and launch.json file, use breakpoints and troubleshoot common problems. Specific steps include: 1. Make sure that Python and Python extensions are installed and select the correct interpreter; 2. Create or modify the launch.json file to configure debugging parameters, such as specifying the run file, console type, and filter library code; 3. Use breakpoints to pause execution and check variables, call stack, and expressions; 4. Solve common problems such as breakpoint misses, scripts not stopping, Python version errors and path issues; 5. Set up custom startup configurations for multi-file projects or web applications to optimize the debugging process.
Debugging Python applications in VS Code is straightforward once you understand the setup and configuration. The editor has built-in support for debugging, and with a few tweaks to your launch.json
file, you can step through code, inspect variables, and evaluate expressions during runtime.
Set Up Your Environment
Before you start debugging, make sure your environment is ready:
- You have Python installed (either system-wide or in a virtual environment).
- The Python extension for VS Code is installed.
- Your workspace is configured to use the correct Python interpreter.
To verify your interpreter path, open the Command Palette ( Ctrl Shift P
or Cmd Shift P
) and select Python: Select Interpreter . This ensures that any debugging uses the right packages and environment.
Also, it helps to keep your project structure clean — ideally, your script or module should be at the root of the workspace or clearly organized so that paths are easy to reference.
Configure launch.json for Debugging
The key file for setting up debugging in VS Code is launch.json
. If it doesn't already exist in your .vscode
folder, you can create it by clicking the Run and Debug icon on the left sidebar, then selecting create a launch.json file .
Here's a basic configuration for running a Python script:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "justMyCode": true } ] }
-
"name"
is what you'll see in the debugger dropdown. -
"program": "${file}"
means it will run the currently open file. -
"console": "integratedTerminal"
allows input/output via the terminal, which is helpful if your script requires user input. -
"justMyCode": true
tells the debugger not to step into libraries, which keeps things focused.
You can also add more configurations for different entry points, such as unit tests or web apps like Flask or Django.
Use Breakpoints and Inspect Variables
Once your configuration is set up, you can start debugging by pressing F5
or clicking the green play button in the Run and Debug panel.
To pause execution:
- Click in the gutter next to a line number to set a breakpoint.
- When the program hits that line, it will pause, allowing you to inspect variables, call stack, and evaluate expressions.
While paused:
- Hover over variables in the editor to see their current values.
- Use the VARIABLES section in the debug sidebar to explore more deeply nested data.
- Use WATCH to track specific expressions or variables across steps.
You can step over lines ( F10
), step into functions ( F11
), or continue until the next breakpoint ( F5
). These controls are also available via the floating debug toolbar at the top of the editor window.
Handle Common Debugging Issues
Sometimes debugging might not work as expected. Here are a few common issues and how to address them:
- Breakpoints don't hit: Make sure
"justMyCode": true
isn't skipping over your code unintentionally. Try setting it tofalse
temporarily. - Script runs but doesn't stop: Double-check that breakpoints are actually enabled. Disabled ones appear gray instead of red.
- Wrong Python version used: Confirm the interpreter selected matches the one you expect. Sometimes VS Code defaults to an older version or global install.
- Path problems: If your script imports modules from other directories, you may need to adjust
PYTHONPATH
in your environment or use relative imports carefully.
For multi-file projects or web apps, consider setting up custom launch configurations that point directly to your app's main module or startup file.
Basically that's it. With a proper setup, debugging in VS Code becomes a powerful part of your development workflow.
The above is the detailed content of How do I debug Python applications in VS Code?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with
