Summary of several methods for debugging Python program code

Source: Internet
Author: User
Tags integer division
The probability that the program can be completed once and run normally is very small, not more than 1%. There will always be a variety of bugs to fix. Some bugs are simple, look at the error message and know that some bugs are complicated, we need to know which variables are correct, and which values are wrong, so a full set of debug programs is required to fix the bug.

The first method, which is straightforward and straightforward, is to print out the variables that might be problematic by printing them to see:

# err.pydef Foo (s):  n = Int (s)  print ' >>> n =%d '% n  return 10/ndef main ():  foo (' 0 ') main ()

After execution, look for the printed variable value in the output:

$ python err.py>>> n = 0Traceback (most recent call last): .... Zerodivisionerror:integer division or modulo by zero

The biggest disadvantage of using print is that it will have to be erased in the future, and that the program is full of print, and the results of the operation contain a lot of junk information. So, we have a second method.
Assertion

Where print is used to assist in viewing, you can replace it with an assertion (assert):

# err.pydef Foo (s):  n = Int (s)  assert n! = 0, ' n is zero! '  return 10/ndef Main ():  foo (' 0 ')

The assert means that the expression n! = 0 should be true, otherwise the subsequent code will go wrong.

If the assertion fails, the Assert statement itself throws Assertionerror:

$ python Err.pytraceback (most recent): ... Assertionerror:n is zero!

If the app is flooded with assert, it's no better than print. However, you can turn off assert with the-o parameter when you start the Python interpreter:

$ python-o Err.pytraceback (most recent): ... Zerodivisionerror:integer division or modulo by zero

When you close, you can see all the assert statements as pass.
Logging

Replacing print with logging is the 3rd way, and the assert ratio, logging does not throw an error, and can be output to a file:

# err.pyimport loggings = ' 0 ' n = Int (s) logging.info (' n =%d '% n) print 10/n

Logging.info () can output a piece of text. Run, found no information except Zerodivisionerror. What's going on?

Don't worry, add a line configuration after import logging and try again:

Import Logginglogging.basicconfig (Level=logging.info)

See the output:

$ python err.pyinfo:root:n = 0Traceback (most recent call last): File "err.py", line 8, in 
 
  
   
    print 10/nzerodi Visionerror:integer division or modulo by zero
 
  

This is the benefit of logging, which allows you to specify the level of logging information, Debug,info,warning,error, and so on, when we specify Level=info, Logging.debug does not work. Similarly, after specifying level=warning, debug and info will not work. This way, you can confidently output different levels of information, do not delete, and finally unified control the output of which level of information.

Another benefit of logging is that with a simple configuration, a single statement can be output to a different place at the same time, such as the console and the file.
Pdb

The 4th Way is to launch the Python debugger pdb, to let the program run in a single step, and to view the running state at any time. Let's prepare the program:

# Err.pys = ' 0 ' n = Int (s) Print 10/n

Then start:

$ python-m pdb err.py>/users/michael/github/sicp/err.py (2)
 
  
   
  ()-s = ' 0 '
 
  

After starting with the parameter-m PDB, the PDB navigates to the next code to execute, s = ' 0 '. Enter command l to view the code:

(Pdb) L 1   # err.py 2-s = ' 0 ' 3   n = Int (s) 4   print 10/n[eof]

Enter command N to step through the code:

(PDB) n>/users/michael/github/sicp/err.py (3)
 
  
   
  (), n = Int (s) (PDB) n>/users/michael/github/ sicp/err.py (4)
  
   
    
   (), print 10/n
  
   
 
  

At any time, you can enter the command p variable name to view the variable:

(PDB) p s ' 0 ' (PDB) p N0

Enter command q to end debugging, exit the program:

(Pdb) Nzerodivisionerror: ' integer division or modulo by zero ' >/users/michael/github/sicp/err.py (4)
 
  
   
  ( ), print 10/n (Pdb) q
 
  

This method of debugging through the PDB in the command line is theoretically omnipotent, but it is too cumbersome, if there are 1000 lines of code, to run to the No. 999 line to knock how many commands ah. Fortunately, we have another debugging method.
Pdb.set_trace ()

This method also uses the PDB, but does not require stepping, we only need to import the PDB, and then, where possible error place a pdb.set_trace (), you can set a breakpoint:

# err.pyimport PDBs = ' 0 ' n = Int (s) pdb.set_trace () # Running here will automatically pause the print 10/n

Running the code, the program will automatically pause in Pdb.set_trace () and go into the PDB debugging environment, you can view the variable with command p, or continue with command C:

$ python err.py >/users/michael/github/sicp/err.py (7)
 
  
   
  (), print 10/n (PDB) p N0 (PDB) ctraceback (MOS T recent: File "err.py", line 7, in 
  
   
    
     print 10/nzerodivisionerror:integer division or modulo by Z Ero
  
   
 
  

This is much more efficient than a direct-start PDB, but it's also a high-level one.
Ide

If you want to set breakpoints more easily, step into it, you need an IDE that supports debugging capabilities. The better Python IDE now has pycharm:

http://www.jetbrains.com/pycharm/

In addition, the Eclipse plus Pydev plugin can also debug Python programs.
Summary

Write a program The most painful thing is debugging, the program will often be in your unexpected process to run, you expect to execute the statement actually did not execute, at this time, it is necessary to debug.

Although debugging with the IDE is convenient, but in the end you will find that logging is the ultimate weapon.

  • 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.