When we finish writing a piece of Python code, it often does not run well normally. That’s when we need to debug the code. Although most IDEs provide support for code debugging, we will talk about 4 fundamental python debugging methods in this article.
1. Print( )
The simplest and most common debugging method is to use
print() statements to print out the suspect variable in the terminal. Almost all programming languages can use
Please see the following code:
After the code runs, check the values of the variable printed out in the terminal to find out the reason for the error — division by zero.
Disadvantages of using print():
- There are many useless
print()in the code, and you have to delete them before the program is released. These operations may pose potential risks to the code.
You can use
assert instead of
print() to debug the code.
Rewrite the above code as follows.
assert statement lets you test if a condition -
number != 0 in your code returns
True, if not, the program will raise an
AssertionError and return an error message(optional).
The command-line option
-O(capital letters) can close
assert. After closing it, you can look at all the
assert statements as
IMPORTANT: Do not add parentheses when using the
assert statement is mainly used for debugging and self-check and the following scenarios cannot use
asset cannot check
For example, to open a file, the following code is incorrect.
assert here, you assume that the file must exist. In a real scenario, the file may not exist, and when you open a file may also trigger other exceptions, so we should use
try…except to handle it.
Because you can simply use the
-O option to turn off
assert checking so that the code in the assert will not be executed. If you put business logic into
assert, such as checking permissions with
assert, doing so will bring huge vulnerability to your code.
The third way is that you can use the logging module to replace the
print(). Let's rewrite the initial example as follows:
Its output looks like this.
logging module provides a lot of functionality and flexibility. It can output messages not only in the terminal but also to a file. Before using the
logging module, you need to set the Logging Levels. There are five levels, from the highest urgency to lowest urgency, are:
The advantages of
Logging compared to
- You can set different levels of urgency for messages, and filter out less urgent messages.
- When you want to later find/remove log messages, you won’t get them confused for real
- If you just print to a log file, it’s easy to leave the log function calls in and just ignore them when you don’t need them.
- With a simple configuration, a single statement can be output to different places at the same time, such as consoles and files.
For a more comprehensive overview of
logging, please refer to the official tutorial(https://docs.python.org/3/library/logging.html).
In the last method, we use python’s built-in debugger
pdb. The module
pdb defines an interactive source code debugger for Python programs.
Let’s look at the example first.
Use the command
-m pdb to start
$python -m pdb pdg-test.py
After starting you can use the command
l to list source code,
n to continue execution until the next line in the current function is reached to its returns,
p expression to evaluate the expression in the current context and print its value, and finial use
q to quit from the debugger.
In addition, you can
import pdb and use
pdb.set_trace() to set breakpoints in your code.
Directly use command
python pdg-debug.py without
-m pdb to run the code. The program will automatically break at the position of
pdb.set_trace() and enter the
pdb debugging environment. You can use the command
p variable to view the variables or use the command
c to continue to run.
Pdb Usage Scenarios
- Debugging large-scale python programs
- Debugging code in a production environment
- Debugging multi-language mixed code
For more information about
pdb, please refer to the official documentation(https://docs.python.org/3/library/pdb.html).
This article introduces 4 ways to debug your Python code besides IDE. During the development phase, it is most convenient to use IDE to debug the code. In addition, according to my experience,
logging is the most practical and powerful.
Thanks for reading.
Take care, and stay all safe and healthy.