How to debug a python module in VSCode
Last Updated :
02 Jul, 2024
Debugging is an essential part of the development process, allowing developers to inspect their code, understand its behavior, and identify and fix issues. Visual Studio Code (VSCode) is a powerful, free code editor that offers robust debugging capabilities for Python. This article will guide you through the process of setting up and using VSCode to debug a Python module, from initial setup to advanced debugging techniques.
What is Debugging in Python?
Debugging is a process in which we identify, analyze, and fix bugs and errors in a Python program. It is a critical process to ensure the proper functioning of the software. To achieve such results we utilize some techniques and tools such as :
- Simple Print() Statements: this is the technique we use when we start learning to code, in this we just add print() statements for the values and expression whose execution flow we want to track.
- Error Messages and Stack Traces: when we execute a Python code with errors the interpreter provides us with an error message with the error type & location, which provides us with the information to debug the code.
- Logging for more detailed Output: Using "logging" modules we can get more control and flexibility to record varying severity of bugs compared to print() statements.
- Interactive Debugging with "pdb": with the help of Python Debugger("pdb") we can set up breakpoints throughout the code and examine the code stepwise inspecting variables interactively.
- Writing and Running Automated Tests: Creating automated tests using tools like "unittest" or "pytest" to automatically verify the functionality of the code.
- Using Static Code Analysis Tool: We can use tools like "pylint", "flaske8" or"mypy" to analyze the code and find potential errors.
- Profiling for Performance Issues: we can use profiling tools like "cProfile" to identify and analyze performance bottlenecks in the code.
- Exception Handling: Implementing "try" and "catch" blocks to manage runtime errors and respond to them gracefully.
- Advanced Tools Provided by IDE: We can utilize integrated debugging features in IDE like breakpoints, variable watching, and call stack inspection.
Setting Up VSCode for Python
Before you can start debugging, you need to ensure that VSCode is properly configured for Python development. This involves installing the necessary extensions and selecting the appropriate Python interpreter.
Configuring the Python Interpreter
Open the command palette in VS Code (can be accessed by pressing 'ctrl + shift + p' [windows] or 'cmd + Shift + p' [ Mac]) and type " Python: Select Interpreter". Choose the interpreter for python for your virtual environment.
Configuring Python Interpreter
Selecting Python InterpreterMake sure VS Code can access the Python interpreter without any issues to check just run a basic Python code such as to print hello world to screen.
Set Up the Python Environment
Open Terminal in VS Code and navigate to your project directory. Create a virtual environment in the project directory by running the following command. This will create a virtual environment with the name 'myvenv'.
python -m venv myenv
Now, you can activate the virtual environment using the following command
On Windows:
myenv\Scripts\activate
On MacOS
source myenv/bin/activate
Python Debug Configuration
To debug your Python code, you need to set up a debug configuration. This configuration tells VSCode how to run and debug your code.
Create a Debug Configuration
First, open the Debug view by clicking on the debug icon in the activity bar. Then click on the gear icon to open the 'launch.json' file. If it doesnt exist, VS Code will prompt you to create one. Choose "Python" from the list of options.
Below is a example for the basic configuration file for debugging.
Python
# launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
Set Breakpoints
Breakpoints allow you to pause the execution of your code at specific lines, so you can inspect the program state. We can set breakpoints by opening the file that we want to debug. Then, click on the ribbon left of the line numbers, a red dot would appear indicating the Breakpoint.
Adding BreakpointsOnce the breakpoints are set, you can see the list of all set breakpoints in 'breakpoints' section under Debug view.
Breakpoints in debug viewWe can also edit a breakpoint to add condition to it, such as stopping only when a variable reaches a certain value. This can be done by right clicking the breakpoint added earlier.
Running and Debugging Python Module
With breakpoints set, you can start the debugging process and step through your code to identify issues.
Start Debugging:
In the Debug view make sure your configuration (e.g.:"Python: Current File") is selected. Click the Green play button (Start Debugging) or press 'F5'. Once you start debugging process, you can see a small clock icon appearing in the debug view.
Debugging startedUsing Debugging Tools
We can use the toolbar to control execution:
- Continue (F5): Runs the program until the next breakpoint.
- Step Over (F10): Executes the next line of code but does not step into functions.
- Step Into (F11): Steps into functions to allow you to debug inside them.
- Step Out (Shift+F11): Steps out of the current function.
- Restart (Ctrl+Shift+F5): Restarts the debugging session.
- Stop (Shift+F5): Stops the debugging session.
- Variables Pane: Inspect variables and their values.
- Watch Pane: Add expressions to watch their values as you step through the code.
- Call Stack Pane: See the call stack of the program.
- Breakpoints Pane: Manage your breakpoints.
- Debug Console: Execute Python commands in the context of the program being debugged.
Inspecting Variables and Expressions
VSCode provides tools to inspect the state of your variables and evaluate expressions while debugging.
Variable Pane
This area, view and inspect the values of the local and the global variables. It shows the variable with their current values at the point of execution. While debug mode, hover your mouse pointer over the variables in the code to assess their current state in a tooltip.
Watch Pane
In the debug view, under the watch section u can add variable and expression to monitor their values throughout the execution. Click '+' to add the variable or expression.
Call Stack Pane
You can view the current call stack to understand the sequence of the function calls leading to the current state of execution.
The Debugging Console
This console allows us to execute Python commands to debug the required python code. You can use it to evaluate expressions, modify variables and call functions.
- Open Debug Console: To open debug console click on the debug console tab in the lower part of the VS Code window.
- Evaluate Expressions: You are directly type and execute python expressions on the debug console.
Advanced Debugging Techniques
VSCode offers advanced debugging features, such as exception breakpoints, logpoints, multi-threaded debugging, and remote debugging.
Conditional Breakpoints
To edit a breakpoint just right click on the breakpoint and select edit breakpoint. You can then add conditions like "x==5" which only breaks when the condition is true.
Exception Breakpoints
Set breakpoints on exceptions to pause execution when specific exceptions are thrown. Click the gear icon in the Breakpoints pane and select "Add Exception Breakpoint.
Function Breakpoint
In the break panel, click the '+' sign to add a function to a breakpoint by entering its name which breaks when the function is called.
Logpoints
They are similar to breakpoints but instead of breaking they log a message to the console. to add them right click on the ribbon left of the line number and select "add Logpoint".
Remote Debugging
Configure launch.json
for remote debugging to connect to a remote Python interpreter, useful for debugging code running on another machine or in a container.
Conclusion
Debugging Python code in VSCode is a powerful way to understand and fix issues in your code. By following the steps you can effectively setup and start you debugging journey in Python.
Similar Reads
How to Install a Python Module?
A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. What is a Python Module?A module can be imported by multiple programs for their application, hence a single code can be used by multiple pr
4 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read
How to import a Python module given the full path?
The Python module is a file consisting of Python code with a set of functions, classes, and variable definitions. The module makes the code reusable and easy to understand. The program that needs to use the module should import that particular module. In this article, we will discuss how to import a
5 min read
How to Fix "Can't Import Numpy in VSCode" in Python?
NumPy is a general-purpose array-processing Python library that provides handy methods and functions for working with n-dimensional arrays. NumPy is short for âNumerical Pythonâ and offers various computing tools such as comprehensive mathematical functions and linear algebra routines. VSCode (Visua
4 min read
How to Install Python py-asn module on Windows?
Py-asn is a Python module that is said to be an extension module. It provides\Enables a fast IP address to Autonomous System Numbers Lookups. It can perform both Current state and Historical state lookups with help from its contained packages. Input can be given as MRT/RIB BGP archive. The module is
2 min read
How to Delete a Module in Excel VBA?
Have you ever seen a text file in a notepad or a source code file in visual studio code? These all are just basic files where you can write some code or information. Similarly, we have modules in excel, each module has its code window, where you can write some code and allow it to automate your repe
3 min read
How to locate a particular module in Python?
In this article, we will see how to locate a particular module in Python. Locating a module means finding the directory from which the module is imported. When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current
3 min read
Built-in Modules in Python
Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and ext
9 min read
C API from Extension Module in Python | Set 2
Prerequisite: C API from Extension Module in Python | Set 1 Let's see an example of a new extension module that loads and uses these API functions that we build up in the previous article. Code #1 : #include "pythonsample.h" /* An extension function that uses the exported API */ static PyO
2 min read
How to check Python Version : Windows, Linux and Mac
Python has multiple versions, and it's important to know which version is installed on your system. This information is crucial because different Python versions may have variations in syntax or libraries, and ensuring you're using the correct version is vital for compatibility with your projects. I
5 min read