Home Backend Development Python Tutorial How to debug Python using the Pdb library and commonly used commands

How to debug Python using the Pdb library and commonly used commands

Feb 25, 2017 am 11:00 AM

Everyone knows that Python comes with its own Pdb library, and it is very convenient to use Pdb to debug Python programs. However, remote debugging and multi-threading cannot be handled by Pdb. Let’s take a look at how to use the Pdb library to debug Python and commonly used commands.

There are many ways to use Pdb to debug

The main ways to use Pdb to debug Python programs are the following three! Let’s introduce one by one

Command line plus -m parameter

Command line to start the target program, add -m parameter, so that the breakpoint is called when testPdb.py is called It is before the first line of program execution

The example display that will be focused on in this article is debugging in this way!

python -m pdb testPdb.py
Copy after login

Debugging in python interactive environment

>>> import pdb
>>> import testPdb
>>> pdb.run('testPdb.test()')
Copy after login

Insert a program into the code

It is more commonly used to insert a program in the middle of the program. Compared with setting a breakpoint in a general IDE and then starting debugging, this method The method is hardcode

if __name__ == "__main__":
 a = 1
 import pdb
 pdb.set_trace()
 b = 2
 c = a + b
 print(c)
Copy after login

and then run the script normally: python testPdb.py to pdb. set_trace()It will be settled there, and then you can see the debugging prompt (Pdb)

The debugging situation for the above small program is as follows:

Prepare the test program

Next, use the first method introduced above to debug the Python program to introduce the commonly used commands of pdb, but at the beginning Beforehand, you must prepare the test program code:

testFun.py

This is a submodule that will be called by the main module for testing. When debugging Pdb, is it possible to trace breakpoints from the main module into the submodule (explanation will follow)

#!/usr/bin/python
# -*- coding: utf-8 -*-

def add(a, b):
 return a + b
Copy after login

testPdb.py

This is the code of the main module being debugged below

#!/usr/bin/python
# -*- coding: utf-8 -*-

def sub(a, b):
 return a - b

if __name__ == "__main__":

 print ''
 import testFun
 i = 0
 a = 1
 while(i < 100):
  a = testFun.add(a, 1)
  i = i + 1
 print "累加结果:", a
 print ""

 for letter in &#39;Pdb&#39;:
  print "当前字母:", letter
 print ""

 fruits = [&#39;banana&#39;, &#39;apple&#39;, &#39;mango&#39;]
 for fruit in fruits:
  print "当前水果:", fruit
 print ""


 ret = 0
 for num in range(10, 12):
  ret = sub(ret, num)
 print &#39;循环结果:&#39;, ret
 print ""

 d = {&#39;abc&#39;: 123, 123: "abc"}
 for (k,v) in d.items():
  print "当前键值对:", k, &#39;-&#39;, v
 print ""
Copy after login

Summary of commonly used commands

Basic commands

h(elp) command: will print the commands available in the current version of Pdb. If you want to query a Command, you can enter h [command] , for example h l View list command

l(ist) command: You can list the code blocks currently to be run

Breakpoint management

b(reak): Set breakpoint

For example, b 12 is to add a breakpoint on line 9 of the current script

For example, b sub is to add a breakpoint at the sub function definition of the current script.

In addition to adding breakpoints in the current script, you can also break other scripts in the current script. Click, take the code used above as an example b testFun.add You can add a breakpoint at the add function in the testFun.py script

If you only use b All existing breakpoints will be displayed

condition bpnumber [condition]: Set a conditional breakpoint, such as condition 2 a==0, which means adding the condition "a==" to the second breakpoint 0”

cl(ear): Delete the breakpoint. If there are parameters behind it, it will be the specified breakpoint; if there are no parameters, it will clear all breakpoints

disable/enable: Disable/activate breakpoints

Program logic control

The commands shown below require you to know the code and line number of the corresponding script, so here we first The screenshot shows the first few lines of code required for the test below

c(ont(inue)), allowing the program to run normally until it encounters the next breakpoint

n(ext), allowing The program runs the next line. If the current statement has a function call, using n will not enter the called function body.

As shown in the figure below, when debugging the script breakpoint to testFun. When add(a, 1), continue to execute n and will not enter the function inside testFun.add(a, 1)

s(tep), similar to n , but if there is currently a function call, then s will enter the called function body

As shown in the figure below, when debugging the script breakpoint to testFun.add(a, 1)# When ##, continue to execute s, you will enter the function definition corresponding to testFun.add(a, 1), although testFun.add is not a function defined in this script

j(ump), let the program jump to the specified line number

If the current line is 10, note: if j 20 is executed, it is equivalent to the program jumping directly to line 20, in the middle In fact, lines 11 to 19 are skipped directly and are not executed at all. Therefore, if there is a variable declaration or object initialization in this code that needs to be used in line 20 or later, it may cause an error when it is used. !

Print important information

a(rgs), prints the parameters of the current function. For example, the picture below shows that after the breakpoint enters

testFun.add, the parameters p of testFun.add

are printed, and a certain variable

## is printed.

#Exit debugging


q, exit debugging directly; or use Ctrl+D to exit

Summary

The process of debugging using Pdb shown above is actually very simple. The article mainly shows the running effect through screenshots. If you simply read the article, you will be very clueless, and you may even feel that the commands and output in the screenshots are messy. However, if you follow the process yourself, it will not take an hour, but the effect will be absolutely excellent! One more thing, Python's debugger is Pdb, which can be used to learn the C debugger gdb under Linux. The above is the entire content of this article. I hope it will be helpful to everyone's study and work.

For more articles on how to use the Pdb library to debug Python and commonly used commands, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles