Home Backend Development Python Tutorial What are the Python debugging methods? I will tell you how to use Python debugging commands in 3 minutes.

What are the Python debugging methods? I will tell you how to use Python debugging commands in 3 minutes.

Aug 23, 2018 pm 05:47 PM

The probability that a programmer can write a program in one go and run it 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. This method is called Debugging Command in programming.

The first method is simple, direct, crude and effective, which is to use print() to print out the variables that may have problems:

def foo(s):
    n = int(s)
    print('>>> n = %d' % n)    return 10 / ndef main():
    foo('0')
main()
Copy after login

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

$ python err.py
>>> n = 0
Traceback (most recent call last):
  ...
ZeroDivisionError: integer division 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 will also contain a lot of junk information. So, we have a second method.

Assertion

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

def foo(s):
    n = int(s)    assert n != 0, 'n is zero!'
    return 10 / ndef main():
    foo('0')
Copy after login

assert means that the expression n != 0 should be True, otherwise, according to the logic of program operation, the following code will definitely 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):
  ...
ZeroDivisionError: division by zero
Copy after login

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

logging

Replacing print() with logging is the third way. Compared with assert, logging will not throw an error and can be output to a file:

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 and find no information except ZeroDivisionError. 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)
ZeroDivisionError: division by zero
Copy after login

This is the benefit of logging, it allows you to specify records The levels of information include 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 the console and files.


The above is the detailed content of What are the Python debugging methods? I will tell you how to use Python debugging commands in 3 minutes.. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles