Python Day 9 (6) debugging

Source: Internet
Author: User
Tags assert

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.

Method One: Print () the variables that may be problematic to see

1 defFoo (s):2n =Int (s)3     Print('>>> n =%d'%N)4     return10/N5 6 defMain ():7Foo'0')8 9Main ()

Find the printed variable value in the output after execution

1 $ python err.py 2 >>> n = 03Traceback (most recent call last):4...   5or modulo by zero

print()The biggest disadvantage is to delete it in the future, think about the program is everywhere print() , the results will contain a lot of junk information.

Method Two: Assertions ( print() any place that is used to assist in viewing can be replaced by assertions (assert))

1 def Foo (s): 2     n = int (s)3     assert'n is zero! ' 4     return / n56def  Main ():7     foo ( ' 0 ')

assertThe expression n != 0 should be True , otherwise, according to the logic of the program run, the following code will definitely go wrong.

If the assertion fails, the assert statement itself is thrownAssertionError

1 $ python err.py 2 Traceback (most recent): 3   ... 4  is zero!

If the program is filled with everywhere assert , and print() compared to where to go. However, you can use -O parameters to turn off the Python interpreter when you start it assert :

1 $ python-O err.py2Traceback (most recent call last):3   ... 4 zerodivisionerror:division by zero

After closing, you can take all the assert statements as a pass look.

Law Three: Logging

and assert ratio, logging will not throw errors, and can be output to a file

1 Import Logging 2 logging.basicconfig (level=logging.info)34'0' 5 n = int (s)6 logging.info ('n =%d' % N) C18>7Print(10/n)

 < Span class= "string" > output is: 
1 $ python err.py 2 info:root:n = 03Traceback (most recent):4   " err.py "  in <module>5     print(Ten/ N)6 zerodivisionerror: Division by zero

 < Span class= "string" > This is the benefit of  logging , which allows you to specify the level of logging information, with  debug ,  Info ,  warning ,  error , and so on, when we specify  level=info ,  logging.debug The  will not work. Similarly, after you specify  level=warning ,  debug  and  info  do 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. 

Law IV: PDB (launches the debugger PDB for Python, which allows the program to run in a single step and can view the running state at any time.)

Program code is:
1 ' 0 ' 2 n = int (s)3print(10/n)

Then start:

1 $ python-m pdb err.py2 >/users/michael/github/learn-python3/samples/debug/ err.py (2) <module>()3'0'

When started with a parameter -m pdb , the PDB navigates to the code to be executed next -> s = ‘0‘ . Enter a command l to view the code

1 (Pdb) L 2   1     #  err.py3   2  '0'4   3     n = int (s)5   4     print(10/n)

Enter a command n to step through the code

1 (PDB) n 2 >/users/michael/github/learn-python3/samples/debug/err.py (3) <module>()3 - > n = int (s)4(Pdb) n5 >/users/michael/github/learn-python3/samples/debug/ err.py (4) <module>()6print(10/n)

You can enter a command at any time p 变量名 to view the variable

1 (PDB) p s 2 ' 0 ' 3 (PDB) p n 4 0

Enter command q to end debugging, exit program

1 (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.

Law V:  pdb.set_trace () (This method also uses the PDB, but does not require stepping, we only need to import PDB , and then, Place a pdb.set_trace () where possible errors can be set a breakpoint )

1 # err.py 2 Import PDB 3 4 ' 0 ' 5 n = int (s)6#  running here will automatically pause 7print(10/n)

Run the code, the program will automatically pdb.set_trace() pause and enter the PDB debugging environment, you can use the command p to view the variable, or c continue to run with the command

1 $ python err.py2>/users/michael/github/learn-python3/samples/debug/err.py (7) <module>()3-Print(10/N)4 (PDB) p n5 06 (PDB) C7 Traceback (most recent):8File"err.py", Line 7,inch<module>9     Print(10/N)TenZerodivisionerror:division by Zero

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

Law VI: 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:

Visual Studio code:https://code.visualstudio.com/, you need to install the Python plugin.

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

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





Python Day 9 (6) debugging

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.