How to Set Breakpoints in Python
In Python, you can set breakpoints and debug using the pdb module.
Here are the steps to set breakpoints and run in Python:
- Importing the pdb module: At the beginning of your Python script, include the statement import pdb.
- Set a breakpoint: Choose the location in the code where you want to set a breakpoint, and add the statement pdb.set_trace() before or after that location.
- Run the program: Execute the Python script in the terminal or command line.
- Enter debug mode: When the program reaches a breakpoint, it will enter the pdb debugging mode. Then, a series of pdb commands can be used for debugging as follows:
- n: Proceed to the next line of code.
- s: enter the function call.
- c: Keep running until the next breakpoint.
- Exit debug mode.
- p
: print the value of the variable. - l: Display the code around the current breakpoint.
- Debugging is finished: once debugging is completed, you can exit debug mode by entering the command “q” and allow the program to continue running.
Here is a simple code example demonstrating how to set breakpoints in Python.
import pdb
def divide(a, b):
result = a / b
return result
x = 10
y = 0
pdb.set_trace() # 设置断点,进入调试模式
z = divide(x, y)
print(z)
After running the above code, it will enter the debugging mode of pdb. In this mode, you can use the command ‘n’ to execute the next line of code, use ‘p z’ to print the value of variable z, and use the command ‘q’ to exit debugging mode.