Use the commands in the PDB module in Python to debug the Python code tutorial, pythonpdb

Source: Internet
Author: User

Use the commands in the PDB module in Python to debug the Python code tutorial, pythonpdb

How many times have you had to change others' code? If you are a member of a development team, you may encounter more times than you want. However, Python has a neat debugging feature (like most other languages), which is very convenient to use. This article is a quick tutorial, hoping it will make your coding life easier.
1. A messy Program

For the purpose of this tutorial, let's look at the simple program under idea.

This program receives two command line parameters and then performs addition and subtraction operations.

(Assume that the user inputs a valid value, so we didn't handle the error in the Code .)
 

import sysdef add(num1=0, num2=0):  return int(num1) + int(num2)def sub(num1=0, num2=0):  return int(num1) - int(num2)def main():  #Assuming our inputs are valid numbers  print sys.argv  addition = add(sys.argv[1], sys.argv[2])  print addition  subtraction = sub(sys.argv[1], sys.argv[2])  print subtractionif __name__ == '__main__':  main()

2. PDB

Python provides a useful module PDB, which is actually an interactive source code debugger.

You need the following two lines of code to use this module.
 

import pdbpdb.set_trace()

Let's take a look at our modified program, which contains some breakpoints.
 

import pdbimport sysdef add(num1=0, num2=0):  return int(num1) + int(num2)def sub(num1=0, num2=0):  return int(num1) - int(num2)def main():  #Assuming our inputs are valid numbers  print sys.argv  pdb.set_trace() # <-- Break point added here  addition = add(sys.argv[1], sys.argv[2])  print addition  subtraction = sub(sys.argv[1], sys.argv[2])  print subtractionif __name__ == '__main__':  main()

3. Execute the program to trigger the debugger

Once the breakpoint is set, you can execute the program as usual.
 

python debugger.py 1 2

The program stops running at the first breakpoint.
 

['debugger.py']> /Users/someuser/debugger.py(15)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb)

We set a breakpoint in row 14th, so we can see that the next row to be executed is row 15th. We can see that the program has been stopped before the execution of row 15th.

Here we have several options. Let's take a look at some Debugging commands in the following steps.
4. Next line-> n

In the prompt of your debugger, enter n to run in the next line.
 

> /Users/someuser/debugger.py(14)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb) n> /Users/someuser/debugger.py(15)main()-> print addition

This will execute the current line of code and prepare to execute the next line.

We can use n to execute the entire program line by line, but it is useless.

As you can see, PDB is not actually in our add function. Next, let's look at several other options that make debugging more interesting.

Note:
A cool feature is that you can click the Enter key to execute previous commands (in this example, you only need to run n ).

5. Print-> p

Next, let's start debugging the program again. (You can click c to bring the PDB to the end or until the next breakpoint, because there are no other breakpoints in the program, and all programs will be executed .)
 

['debugger.py', '1', '2']> /Users/someuser/debugger.py(14)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb)

If you want to know what sys. argv contains, enter the following content:
 

-> addition = add(sys.argv[1], sys.argv[2])(Pdb) p sys.argv['debugger.py', '1', '2'](Pdb) p sys.argv[1]'1'(Pdb)

Using this method, you can easily view the values actually stored in the variable.

Now we will enter the interior of the addition function.
6. One step-> s

We can use "s" to enter the addition function.

(Pdb) s--Call--> /Users/someuser/debugger.py(4)add()-> def add(num1=0, num2=0):(Pdb) n> /Users/someuser/debugger.py(5)add()-> return int(num1) + int(num2)(Pdb)

This will bring us into the interior of the addition function. Now we can use n, p, and other operation commands inside the addition function.

Click "r" to bring us to the front of the Return Statement of the function.

This command is useful if you want to quickly jump to the end of a function.
7. dynamically Add a breakpoint-> B

Before running the program, we used pdb. set_trace () to set a breakpoint.

However, we often want to add breakpoints in a specific place in the program after the debugging session has started.

Here we can use option "B" to achieve this purpose.

Run the program again.
 

['debugger.py', '1', '2']> /Users/someuser/debugger.py(15)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb)

At this time, I set a breakpoint in row 18th.
 

-> addition = add(sys.argv[1], sys.argv[2])(Pdb) b 18Breakpoint 1 at /Users/someuser/debugger.py:18(Pdb) cWe are in add--3> /Users/someuser/debugger.py(18)main()-> print subtraction(Pdb) p subtraction-1(Pdb)

From the above we can see that PDB jumped to 18th lines and waited for the next command.

In addition, PDB assigns a number (in this example, 1) to the breakpoint ). For future execution, we can enable or disable the breakpoint number to enable or disable the corresponding breakpoint.
8. List-> l

Sometimes, when debugging, you may forget where you are in the code. In this case, the use of "l" will print a friendly summary, which can display your position in the code at the moment.
 

['debugger.py', '1', '2']> /Users/someuser/debugger.py(15)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb) l 10 11   def main(): 12     #Assuming our inputs are valid numbers 13     print sys.argv 14     pdb.set_trace() # <-- Break point added here 15 ->   addition = add(sys.argv[1], sys.argv[2]) 16     print addition 17     subtraction = sub(sys.argv[1], sys.argv[2]) 18     print subtraction

9. dynamically allocate Variables

During the debugging session, you can assign variables to help you perform debugging. Knowing these variables is also helpful to you. For example:
 

['debugger.py', '1', '2']> /Users/someuser/debugger.py(15)main()-> addition = add(sys.argv[1], sys.argv[2])(Pdb) nWe are in add--> /Users/someuser/debugger.py(16)main()-> print addition(Pdb) p addition3 #<--- addition here is 3(Pdb) addition = 'this is now string' #<--- We changed the value of additon(Pdb) nthis is now string #<--- Now when we print it we actually gets it as a string. that we just set above.> /Users/someuser/debugger.py(17)main()-> subtraction = sub(sys.argv[1], sys.argv[2])

Note:
If you want to set some variables such as n (PDB command), you should use this command:
 

(Pdb) !n=5(Pdb) p n5

10. End-> q

Finally, if you want to end debugging anywhere in the code, you can use "q", then the program being executed will be terminated.
11. Extended reading

This article only covers the surface usage of PDB. In fact, you can do more with PDB (PDB document ).

IPython users can find a better Debugger in ipdb, which provides tab addition, syntax highlighting, and other cool features.

Related Article

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.