Running a Python script in debug mode allows you to analyze and troubleshoot any issues that may arise during execution.
Debug mode provides you with a flow of the code and helps you to identify bugs or logical errors that might exist.
In Linux, you can run a Python script in debug mode by using an Integrated Development Environment (IDE) such as PyCharm or running a command through the terminal.
This tutorial will show you how to run a Python script in debug mode using the terminal in Linux.
Step 1: Install Python
If you haven’t already installed Python on your Linux system, you can do so by running the following command in the terminal:
1 |
sudo apt-get install python3 |
This command will install the latest version of Python on your system.
Step 2: Install Python Debugger (PDB)
Python Debugger (PDB) is a built-in module that allows you to debug your Python code. You can install PDB on your system using the following command:
1 |
sudo apt-get install python3-pdb |
Step 3: Add Debugging Lines in Your Python Script
To enable debugging in your Python script, you should add the following code snippet at the point where you want to start the debugging process:
1 2 |
import pdb pdb.set_trace() |
This code will set a breakpoint in your code and allow you to interactively debug your script.
Step 4: Run Debug Mode in the Terminal
To run the Python script in debug mode using the terminal, you can use the following command:
1 |
python3 -m pdb your_script_name.py |
Replace “your_script_name.py” with the actual name of your Python script. This command will invoke Python Debugger (PDB) and start the debug mode for your script.
Step 5: Debugging Your Script
Once you run the script in debug mode, you will see a “(Pdb)” prompt in the terminal. This prompt signifies that the debugging mode is active, and you can now use various commands to debug your script. You can use the following commonly used commands to control the debugging process:
- n – Executes the current line and moves to the next one
- s – Executes the current line and steps into a function
- c – Continue execution until a breakpoint is reached
- p variable_name – Display the value of a variable
You can also use other commands to list variables, modify values, and step in and out of function calls. A complete list of commands can be found on the official Python documentation page.
Conclusion
Running a Python script in debug mode can be a handy tool that helps you to quickly troubleshoot and debug your code. By adding the necessary debugging lines in your script and running it in debug mode, you can conveniently find and fix bugs that may exist.
1 2 3 4 5 6 7 8 |
import pdb def count_to_n(n): for i in range(n): pdb.set_trace() print(i) count_to_n(5) |
The above code is a sample Python script that includes debugging lines. When you run this script in debug mode, you will be able to see the value of “i” and identify any logical bugs that may exist in the code.