When we write code, we often get a lot of mistakes. How do we debug it?
Print with the print statement
We can print the content we want with the print statement and then view it in the output.
Print "hah"
But after debugging, we also need to manually delete the print statement, more trouble.
Assert
In front of the print, we can use the Assert statement instead. For example:
def foo (s): s = Int (s) assert s! = 0, "s is Zero" return 10.0/sfoo (' 0 ')
The Assert statement is followed by a sentence of judgment, with the error message. If the judgment statement does not conform, a assertionerror is thrown. For example:
Traceback (most recent): File "/users/w/code/python/demo/assertdemo.py", line 7, in Foo (' 0 ') file "/users/w/code /python/demo/assertdemo.py ", line 3, in Fooassert s! = 0," s is zero "assertionerror:s is zero
We can take the parameter at the time of execution with the-O unified close assert. When off, the Assert statement is no longer valid.
Logging
You can replace the print statement with logging. Logging does not throw an error message like an assert. There are many benefits to logging, and one is the ability to make output-specific levels of information.
Level:critical Numeric value:50 level:error Numeric value:40level:warning Numeric value:30 level:info Numeric value : 20level:debug Numeric value:10level:notset Numeric value:0
We can use
Logging.basicconfig (level=logging. DEBUG)
Simple configuration of the logging. Warning that are smaller than this level are ignored. In addition, we can also configure the location of the logging output, such as output to the console or to a debug file. For more logging configuration, you can read: Https://segmentfault.com/a/11 ....
Debugger Pdb,the Python Debugger
The PDB is started in a way that
PYTHON-M PDB test.py
Commands commonly used by PDB
N: Next, which is used to perform the next step
L: Should be a list, see the code below to execute
P variable name: p should be the first letter of parameter to see the value of a variable
Q:quit, exiting the program
The PDB can control the step-by-step implementation of Python, which in theory is a magnum debugger. But when it comes to long code, it becomes inefficient. To analyze our needs, we actually need to set breakpoints at some key points, so let's look at the results of the execution instead of looking at each step as we did earlier. Next we'll take a look at Pdb.set_trace ().
Pdb.set_trace ()
We just need to write a line of code where the program pauses:
Pdb.set_trace ()
When the Python editor encounters Pdb.set_trace (), the program pauses and we can see the values of each parameter using the PDB command mentioned above.
Of course, many modern Ides such as Pycharm provide a lot of convenient visual debugging tools, can be very convenient to get started.
The above is the Python learning note-python debugging content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!