Python day 9 (6) debugging, pythonday

Source: Internet
Author: User
Tags integer division

Python day 9 (6) debugging, pythonday

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.

Method 1: Use the print () function to print out the variables that may be faulty.

1 def foo(s):2     n = int(s)3     print('>>> n = %d' % n)4     return 10 / n5 6 def main():7     foo('0')8 9 main()

Search for printed variable values in the output after execution

1 $ python err.py2 >>> n = 03 Traceback (most recent call last):4   ...5 ZeroDivisionError: integer division or modulo by zero

Useprint()The biggest disadvantage is that you have to delete it in the future.print()The running result also contains a lot of junk information.

Method 2: assertionprint()Can be replaced by assert)

1 def foo(s):2     n = int(s)3     assert n != 0, 'n is zero!'4     return 10 / n5 6 def main():7     foo('0')

 

assertThe expressionn != 0It should beTrueOtherwise, according to the program running logic, the subsequent code will certainly fail.

If the assertion fails,assertThe statement itself throwsAssertionError

1 $ python err.py2 Traceback (most recent call last):3   ...4 AssertionError: n is zero!

 

If the program is filledassert, Andprint()In comparison. However, you can use-OParameter to closeassert:

1 $ python -O err.py2 Traceback (most recent call last):3   ...4 ZeroDivisionError: division by zero

 

After closing, you canassertStatementpassLet's see.

Method 3: logging

AndassertRatio,loggingNo error is thrown and can be output to a file.

1 import logging2 logging.basicConfig(level=logging.INFO)3 4 s = '0'5 n = int(s)6 logging.info('n = %d' % n)7 print(10 / n)

 

Output:
1 $ python err.py2 INFO:root:n = 03 Traceback (most recent call last):4   File "err.py", line 8, in <module>5     print(10 / n)6 ZeroDivisionError: division by zero

 

This isloggingIt allows you to specify the record information level.debug,info,warning,errorWhen we specifylevel=INFO,logging.debugIt does not work. Similarly, specifylevel=WARNINGAfter,debugAndinfoIt does not work. In this way, you can output different levels of information without deleting it, and finally control the output level.

Method 4: pdb (start the Python debugger pdb to allow the program to run in one step. You can view the running status at any time .)

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

Then start:

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

 

Take Parameters-m pdbAfter it is started, pdb locates the code to be executed next.-> s = '0'. Enter the commandlTo view the code

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

 

Enter the commandnCode execution in one step

1 (Pdb) n2 > /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>()6 -> print(10 / n)

 

You can enter commands at any time.P variable nameTo view Variables

1 (Pdb) p s2 '0'3 (Pdb) p n4 0

 

Enter the commandqEnd debugging and exit the program

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

 

Method 5: pdb. set_trace () (This method also uses pdb, but we only needimport pdbThen, putpdb.set_trace()To set a breakpoint)

1 # err. py2 import pdb3 4 s = '0' 5 n = int (s) 6 pdb. set_trace () # The 7 print (10/n) is automatically paused when it runs here)

 

Run the code, the program will automaticallypdb.set_trace()Pause and enter the pdb debugging environment. You can use the commandpView variables or use commandscContinue running

 1 $ python err.py  2 > /Users/michael/Github/learn-python3/samples/debug/err.py(7)<module>() 3 -> print(10 / n) 4 (Pdb) p n 5 0 6 (Pdb) c 7 Traceback (most recent call last): 8   File "err.py", line 7, in <module> 9     print(10 / n)10 ZeroDivisionError: division by zero

 

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

 

Method 6: IDE

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

Visual Studio Code: https://code.visualstudio.com/, install the pythonplug-in.

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 





 

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.