Home > Backend Development > Python Tutorial > How to debug python?

How to debug python?

青灯夜游
Release: 2020-09-17 16:13:24
Original
16385 people have browsed it

The probability that the program can be written once and run normally is very small, basically no more than 1%. There are always various bugs that need to be fixed. Some bugs are very simple. You can tell by looking at the error message. Some bugs are very complicated. We need to know which variables have correct values ​​and which variables have wrong values ​​when an error occurs. Therefore, we need a complete set of means to debug the program. to fix the bug. The following article will introduce you to the python debugging method. I hope it will be helpful to you.

How to debug python?

Method 1: print

Use print to print out the variables that may have problems. This method is the simplest. Direct brutality is effective.

# err.py
def foo(s):
  n = int(s)
  print '>>> n = %d' % n
  return 10 / n

def main():
  foo('0')

main()
Copy after login

After execution, find the printed variable value in the output:

$ python err.py
>>> n = 0
Traceback (most recent call last):
 ...
ZeropisionError: integer pision or modulo by zero
Copy after login

The biggest disadvantage of using print is that you have to delete it in the future. Think about the fact that print is everywhere in the program, and the running results are also It will contain a lot of spam.

Method 2: assert

Wherever print is used to assist viewing, assertion can be used instead:

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

def main():
  foo('0')
Copy after login

assert means that the expression n != 0 should be True, otherwise, the following code will go wrong.

If the assertion fails, the assert statement itself will throw an AssertionError:

$ python err.py
Traceback (most recent call last):
 ...
AssertionError: n is zero!
Copy after login

If the program is full of asserts, it will be no better than print. However, you can use the -O parameter to turn off assert when starting the Python interpreter:

$ python -O err.py
Traceback (most recent call last):
 ...
ZeropisionError: integer pision or modulo by zero
Copy after login

After turning it off, you can view all assert statements as passes.

Method 3: logging

You can also replace print with logging. Compared with assert, logging will not throw an error and can be output to a file:

# err.py
import logging

s = '0'
n = int(s)
logging.info('n = %d' % n)
print 10 / n
Copy after login

logging.info() can output a piece of text. Run it and find that there is no information except ZeropisionError. what happened?

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

import logging
logging.basicConfig(level=logging.INFO)
Copy after login

See the output:

$ python err.py
INFO:root:n = 0
Traceback (most recent call last):
 File "err.py", line 8, in <module>
  print 10 / n
ZeropisionError: integer pision or modulo by zero
Copy after login

This is the benefit of logging, it allows You specify the level of logging information, including debug, info, warning, error, etc. When we specify level=INFO, logging.debug will not work. In the same way, after specifying level=WARNING, debug and info will not work. In this way, you can safely output different levels of information without deleting it, and finally control which level of information is output.

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

Method 4: Debugger pdb

Start the Python debugger pdb, let the program run in single-step mode, and you can check the running status at any time. We first prepare the program:

# err.py
s = &#39;0&#39;
n = int(s)
print 10 / n
Copy after login

Then start:

$ python -m pdb err.py
> /Users/michael/Github/sicp/err.py(2)<module>()
-> s = &#39;0&#39;
Copy after login

After starting pdb with the parameter -m, 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 = &#39;0&#39;
 3   n = int(s)
 4   print 10 / n
[EOF]
Copy after login

Enter the command n to single-step the code:

(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
Copy after login

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

(Pdb) p s
&#39;0&#39;
(Pdb) p n
0
Copy after login

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

(Pdb) n
ZeropisionError: &#39;integer pision or modulo by zero&#39;
> /Users/michael/Github/sicp/err.py(4)<module>()
-> print 10 / n
(Pdb) q
Copy after login

This method of debugging on the command line through pdb is theoretically omnipotent, but it is really troublesome. If there are a thousand lines of code, it must be run until the first How many commands does it take to type 999 lines?

Summary

The most painful thing about writing a program is debugging. The program often runs in an unexpected process, and the statements you expect to be executed are not executed at all. , at this time, debugging is needed.

Related learning recommendations: python tutorial

The above is the detailed content of How to debug python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template