Summary of several methods for debugging Python program code:

Source: Internet
Author: User
Tags integer division

Summary of several methods for debugging Python program code:

The probability that the program can be written and run normally at a time is very small, basically no more than 1%. There will always be various bugs to be corrected. Some bugs are very simple. You can see the error information. Some bugs are very complicated. We need to know which variables are correct and which variables are wrong when an error occurs. Therefore, A complete set of debugging methods are required to fix bugs.

The first method is simple, straightforward, and effective, that is, print out the variables that may be faulty with print:

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

Find the printed variable value in the output after execution:

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

The biggest disadvantage of using print is that you have to delete it in the future. Think about print everywhere in the program, and the running result will also contain a lot of junk information. Therefore, we have another method.
Assertions

Where print is used for viewing, assert can be used instead:

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

Assert means expression n! = 0 should be True. Otherwise, an error will occur in the subsequent code.

If the assert statement fails, the AssertionError is thrown:

$ python err.pyTraceback (most recent call last): ...AssertionError: n is zero!

If assert is everywhere in the program, it is no better than print. However, when starting the Python interpreter, you can use the-O parameter to disable assert:

$ python -O err.pyTraceback (most recent call last): ...ZeroDivisionError: integer division or modulo by zero

After it is disabled, you can view all the assert statements as pass statements.
Logging

Replace print with logging in the following 3rd methods. Compared with assert, logging does not throw errors and can be output to files:

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

Logging.info () can output a piece of text. Run and found that there is no information except ZeroDivisionError. What's going on?

Don't worry. Add a line of configuration after import logging and try again:

import logginglogging.basicConfig(level=logging.INFO)

The output is as follows:

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

This is the benefit of logging. It allows you to specify the record information level, including debug, info, warning, and error. When we specify level = INFO, logging. debug does not work. Similarly, after level = WARNING is specified, debug and info do not work. In this way, you can output different levels of information without deleting it, and finally control the output level.

Another advantage of logging is that through simple configuration, a statement can be output to different places at the same time, such as the console and files.
Pdb

The 4th method is to start the Python debugger pdb so that the program runs in one step and the running status can be viewed at any time. Prepare the program first:

# err.pys = '0'n = int(s)print 10 / n

Then start:

$ python -m pdb err.py> /Users/michael/Github/sicp/err.py(2)<module>()-> s = '0'

After starting with the-m pdb parameter, pdb locates the code to be executed next-> s = '0 '. Enter the command l to view the Code:

(Pdb) l 1   # err.py 2 -> s = '0' 3   n = int(s) 4   print 10 / n[EOF]

Enter the command n to execute the code in one step:

(Pdb) n> /Users/michael/Github/sicp/err.py(3)<module>()-> n = int(s)(Pdb) n> /Users/michael/Github/sicp/err.py(4)<module>()-> print 10 / n

You can enter the p variable name to view the variable at any time:

(Pdb) p s'0'(Pdb) p n0

Enter the q command to end debugging and exit the program:

(Pdb) nZeroDivisionError: 'integer division or modulo by zero'> /Users/michael/Github/sicp/err.py(4)<module>()-> print 10 / n(Pdb) q

In theory, this method of debugging through pdb is omnipotent, but it is too troublesome. If there are one thousand lines of code, how many commands are required to run to 999th lines. Fortunately, we have another debugging method.
Pdb. set_trace ()

This method also uses pdb, but does not need to be executed in a single step. We only need to import pdb, and then put a pdb. set_trace () in the place where an error may occur to set a breakpoint:

# Err. pyimport pdbs = '0' n = int (s) pdb. set_trace () # print 10/n is automatically paused when running here.

Run the code. The program will automatically pause in pdb. set_trace () and enter the pdb debugging environment. You can run the command p to view the variable, or run the command c:

$ python err.py > /Users/michael/Github/sicp/err.py(7)<module>()-> print 10 / n(Pdb) p n0(Pdb) cTraceback (most recent call last): File "err.py", line 7, in <module>  print 10 / nZeroDivisionError: integer division or modulo by zero

This method is much more efficient than directly starting pdb for single-step debugging, but it is also less efficient.
IDE

If you want to easily set breakpoints and perform one-step operations, you need an IDE that supports debugging. Currently, Python IDE is better equipped with PyCharm:

Http://www.jetbrains.com/pycharm/

In addition, you can also debug Python programs by adding the pydev plug-in to Eclipse.
Summary

Debugging is the most painful thing to write a program. The program runs with unexpected processes. The statements you expect to execute are not executed at all. At this time, debugging is required.

Although it is easier to debug with IDE, you will find that logging is the fuse 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.