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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles