Debugging a Python program instance using the PDB module

Source: Internet
Author: User
In Python, syntax errors can be found by the Python interpreter, but logical errors or variable usage errors are not easy to find, and if the results do not meet expectations, debugging is a good debugging tool: The PDB module that comes with Python. The PDB is the debug module that comes with Python. Use the PDB module to set breakpoints, step through, view variable values, and so on for a script.

The PDB can be started with command-line arguments, or it can be imported and reused using import.

The code is as follows:


>>> dir (PDB)
[' Pdb ', ' repr ', ' Restart ', ' testCMD ',....., ' re ', ' Run ', ' Runcall ', ' runctx ', ' runeval ', ' set_trace ', ' sys ', ' Test ', ' Trac Eback ']


The common PDB functions are as follows:

"Pdb.run () function"

>>> This function is mainly used for debugging statement blocks
>>> basic usage is as follows

The code is as follows:


>>> Help (Pdb.run)
Help on function run in module PDB:

Run (statement, Globals=none, Locals=none)
>>> parameter meaning

Statement: The block of statements to be debugged, expressed as a string
Globals: Optional parameter to set global environment variables for statement run
Locals: Optional parameter to set local environment variables for statement run
>>> Simple Example

The code is as follows:


>>> Import PDB # importing Debug modules
>>> Pdb.run ("" # Call the Run () function to execute a for loop
For I in range (3):
I *= 3
Print (i)
''')
> (2) ()
(PDB) n # (PDB) is a debug command prompt, indicating that a debug command can be entered
> (3) ()
(PDB) n # N (next) indicates execution of the next line
> (4) ()
(Pdb) print (i) # Prints the value of the variable i
0
(PDB) Continue # Continue running the program
0
3
6

"Pdb.runeval () function"
>>> This function is primarily used for debugging expressions
>>> basic usage is as follows

The code is as follows:


>>> Help (Pdb.runeval)
Help on function runeval in module PDB:

Runeval (expression, Globals=none, Locals=none)

>>> parameter meaning

Expression: To debug,
Globals: Optional parameter to set global environment variables for statement run
Locals: Optional parameter to set local environment variables for statement run

>>> Simple Example

The code is as follows:


>>> Import PDB # importing PDB modules
>>> LST = [1, 2, 3] # define a list
>>> pdb.runeval (' lst[1] ') # Call the Runaval () function to debug an expression lst[1]
> (1) ()
(PDB) n # Enter the debug state, using the n command, stepping
--return--
> (1) ()->2
(PDB) n # Single Step execution
2 # Returns the value of an expression
>>> Pdb.runeval (' 3 + 5*6/2 ') # Use the Runaval () function to debug an expression 3+5*6/2
> (1) ()->2
(PDB) n
--return--
> (1) ()->18
(PDB) n # step with n command
18 # The value of the expression is finally reached

"Pdb.runcall () function"

>>> This function is mainly used for debugging functions
>>> basic usage is as follows

The code is as follows:


>>> Help (Pdb.runcall)
Help on function Runcall in module PDB:

Runcall (*args, **kwds)

>>> parameter meaning
Function: Name of function
Args (Kwds): Parameters of a function
>>> Simple Example

The code is as follows:


>>> Import PDB # importing module
>>> def sum (*args): # defines the sum of functions, and asks for all parameters
res = 0
For Arg in args:
Res + = arg
return res

>>> pdb.runcall (SUM, 1, 2, 3, 4) # Use the Runcall debug function sum
> (2) sum ()
(PDB) n # enters debug state, stepping
> (3) sum ()
(PDB) n # Single Step execution
> (4) sum ()
(Pdb) print (res) # Prints the value of res with print
0
(PDB) Continue # Continue execution
10
>>> pdb.runcall (SUM, 1, 2, 3, 4, 5, 6) # call Runcall debug function sum with different arguments

> (2) sum ()
(PDB) Continue # Continue execution
21 # Function finally returns the result

"Pdb.set_trace () function"

>>> This function is primarily used to set a hard breakpoint in a script
>>> basic usage is as follows

The code is as follows:


>>> Help (Pdb.set_trace)
Help on function set_trace in module PDB:

Set_trace ()

>>> Simple Example

The code is as follows:


# file:test.py

Import PDB

Pdb.set_trace ()
For I in range (5):
I *= 5
Print (i)

After running the script, it displays:

The code is as follows:


> d:\learn\python\test.py (6) ()
-I in range (5):
(Pdb) List # list script contents using list
1 # file:test.py
2
3 Import PDB
4
5 pdb.set_trace () # Use Set_trace () to set a hard breakpoint
6-for-I in range (5):
7 I *= 5
8 Print (i)
[EOF] # List the end of script content
(PDB) Continue # Continue execution with continue
0
5
10
15
20

"PDB debug Command"
The debug commands in the PDB can complete stepping, printing variable values, setting breakpoints, and more. The PDB main commands are as follows

The code is as follows:


------------------------------------------------------------------------------
# full Command Shorthand command description
------------------------------------------------------------------------------
# args A prints the parameters of the current function
# Break B Set Breakpoints
# Clear CL Clears breakpoints
# Condition no conditional breakpoint set
# Continue C continues to run until a breakpoint is encountered or the script ends
# Disable No Disable breakpoint
# Enable no breakpoint enabled
# help H View PDB assistance
# Ignore No Ignore breakpoint
# Jump J jumps to the specified number of lines run
# list L List script list
# Next N Executes the next statement, encountering the function not entering its interior
# print p Prints variable values
# Quit Q Exit PDB
# return R runs uniformly to function return
# Tbreak No temporary breakpoints, breakpoints are interrupted only once
# step S executes the next statement, encounters a function into its interior
# where W to see where
# ! No statements are executed in the PDB


>>> Simple Example

The code is as follows:


#-*-CODING:GBK-*-
# file:prime.py
#
Import Math
# IsPrime function Determines whether an integer is a prime number
# If I can be divisible by any number within the square root of 2 to I,
# Then I is not a prime, return 0, otherwise I is a prime number, return 1.
def isprime (i):
For T in range (2, int (math.sqrt (i)) + 1):
If I% T = = 0:
return 0


Print (' 100~110 between primes: ')
For I in range (100, 110):
If IsPrime (i):
Print (i)

Run the following command first:

The code is as follows:


D:\LEARN\PYTHON>PYTHON-M PDB prime.py

Then enter the following command:

The code is as follows:


D:\LEARN\PYTHON>PYTHON-M PDB prime.py
> d:\learn\python\prime.py (4) ()
Import Math
(Pdb) List # Run the previous command and stop here, list defaults to only 11 rows
1 #-*-CODING:GBK-*-
2 # file:prime.py
3 #
Import Math 4
5 # IsPrime function Determines whether an integer is a prime number
6 # If I can be divisible by any number within the square root of 2 to I,
7 # Then I is not a prime, return 0, otherwise I is a prime number, return 1.
8 def isprime (i):
9 for T in range (2, int (math.sqrt (i)) + 1):
If I% T = = 0:
return 0
(Pdb) L 14,17 # Use the list command to list 14 rows to 17 rows
Print (' 100~110 between primes: ')
For I in range (100, 110):
If IsPrime (i):
Print (i)
(Pdb) b 14 # Set breakpoints with the break command
Breakpoint 1 at D:\learn\python\prime.py:14 # return breakpoint Number: 1
(Pdb) b isprime # Set breakpoints in function IsPrime
Breakpoint 2 at D:\learn\python\prime.py:8 # return breakpoint Number: 2
(PDB) C # Run script running with c command
> d:\learn\python\prime.py (14) () # Stop at Breakpoint 1, line 14th
-Print (' 100~110 between the primes: ')
(PDB) C # Continue running scripts with C command
The prime numbers between 100~110 are: # line 14th script output
> d:\learn\python\prime.py (9) IsPrime () # Stops at Breakpoint 2, which is the IsPrime function
-for-T in range (2, int (math.sqrt (i)) + 1):
(Pdb) b 15 # Set breakpoints at line 15th
Breakpoint 3 at D:\learn\python\prime.py:15
(Pdb) Disable 2 # Disables breakpoint 2, which is the breakpoint at the IsPrime function
(PDB) C # Continue running scripts with C command
> d:\learn\python\prime.py (15) () # Stop at Breakpoint 3, line 15th
-I in range (100, 110):
(Pdb) print (i) # Prints the value of the variable i using print
100
(PDB) C # continue running script
> d:\learn\python\prime.py ( ) ()
-I in range (100, 110):
(PDB) P I # Print the value of I
101
(PDB) Enable 2 # Restore Breakpoint 2, which is the breakpoint at the IsPrime function
(PDB) C # continue running script
> d:\learn\python\prime.py (9) IsPrime ()
-for-T in range (2, int (math.sqrt (i)) + 1):
(PDB) n # stepping into the next statement
> d:\learn\python\prime.py (Ten) IsPrime ()
If I% T = = 0:
(Pdb) print (t) # Prints the value of the variable t using print
2
(PDB) CL # Clear All breakpoints, enter Y to confirm
Clear all breaks? Y
(PDB) C # continue running script
103
105
107
109
(PDB) Q # exit Pdb debug using Quit (q)

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.