Python code debugging

Source: Internet
Author: User
Tags stack trace
ArticleDirectory
    • 1. Print Output
    • 2. Logging Module

I did not like debugging very much.ProgramI feel that debugging is also necessary. I would like to briefly summarize several common debugging methods.

1. Print Output

Do not underestimate the print output. Sometimes, it may be the fastest way. Use print to output the value of a variable and compare it with the expected value. If there is a problem, analyze the source code to see where there is an error.

2. Logging Module

This module is powerful and useful, and can replace print. The logging module can define the log level, includingNotset <debug <info <warning <error <critical. By setting this, You can output logs of a higher level. You can choose to save the logs to a file or output the logs on the screen. For more information, see the python manual.

3. Write in bpythonCode

The advantage of this editor is that it is executed immediately after writing a line of code, and then we can immediately see the result. If there is a problem, we can immediately undo the code and save the code after writing. The code prompt function is also powerful.

4. Use Python-I to execute code

After this execution, the program does not exit immediately. Instead, open a python interactive command line interface. Here we can execute some commands, such as Dir (), to view variables and functions, and directly enter the variable name to view the value of the variable. If the program exits unexpectedly, it will also retain the "site". We can analyze the site and find the error.

5. PDB debugging

Finally, let's talk about this artifact.

After reading the official documentation, the PDB module is implemented using the BDP module and the CMD module. Implement functions similar to PDB.

The simple way to use this module is to set the breakpoint, first import the PDB module, and then execute it where you need to stop.PDB. set_trace () command, so that the program will stop when executing this command, and then we can enter some PDB commands for debugging. You can execute the statement in one step, continue to execute the statement, view the value of the variable, and execute some statements to display the code block to be executed, so that the program can jump to and execute other statements.

For detailed commands, refer to the official documentation:

 H (ELP) [command] Without argument, print the list of available commands. with a command as argument, print help about that command. help PDB displays the full documentation file; if the environment variable pager is defined, the file is piped through that command instead. since thecommand argument must be an identifier, help exec must be entered to get help on! Command. W (here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the current frame, which determines the context of most commands. D (own) Move the current frame one level down in the stack trace (to a newer frame ). U (P) Move the current frame one level up in the stack trace (to an older frame ). B (reak) [[filename:] lineno | function [, condition] With a lineno argument, set a break there in the current file. with a function argument, set a break at the first executable statement within that function. the line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet ). the file is searched on sys. path. note that each breakpoint is assigned a number to which all the other breakpoint commands refer. if a second argument is present, it is an expression which must evaluate to true before the breakpoint is honored. without argument, list all breaks, including for each breakpoint, the number of times that breakpoint has been hit, the current ignore count, and the associated condition if any. Tbreak [[filename:] lineno | function [, condition] Temporary breakpoint, which is removed automatically when it is first hit. The arguments are the same as break.CL (EAR) [filename: lineno | bpnumber [bpnumber...] With a filename: lineno argument, clear all the breakpoints at this line. with a space separated list of breakpoint numbers, clear those breakpoints. without argument, clear all breaks (but first ask confirmation ). Disable [bpnumber [bpnumber...] Disables the breakpoints given as a space separated list of breakpoint numbers. disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-) enabled. Enable [bpnumber [bpnumber...] Enables the breakpoints specified. Ignore bpnumber [count] Sets the ignore count for the given breakpoint number. if count is omitted, the ignore count is set to 0. a breakpoint becomes active when the ignore count is zero. when non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true. Condition bpnumber [condition] Condition is an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; I. e., the breakpoint is made unconditional. Commands [bpnumber] Specify a list of commands for breakpoint number bpnumber. the commands themselves appear on the following lines. type A line containing just 'end' to terminate the commands. an example :( PDB) commands 1 (COM) print some_variable (COM) end (PDB) to remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. with no bpnumber argument, commands refers to the last breakpoint set. you can use breakpoint commands to start your program up again. simply use the continue command, or step, or any other command that resumes execution. specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command List (as if that command was immediately followed by end ). this is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint-which cocould have its own command list, leading to ambiguities about which list to execute. if you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. this may be desirable for breakpoints that are to print a specific message and then continue. if none of the other commands print anything, you see no sign that the breakpoint was reached. new in version 2.5.S (TEP) Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function ). N (EXT) Continue execution until the next line in the current function is reached or it returns. (the difference between next and step is that stepstops inside a called function, while next executes called functions at (nearly) full speed, only stopping at the next line in the current function .) Unt (IL) Continue execution until the line with the line number greater than the current one is reached or when returning from current frame. New in version 2.6. R (eturn) Continue execution until the current function returns. C (ONT (inue )) Continue execution, only stop when a breakpoint is encountered.J (UMP) lineno Set the next line that will be executed. only available in the bottom-most frame. this lets you jump back and execute code again, or jump forward to skip code that you don't need want to run. it shoshould be noted that not all jumps are allowed-for instance it is not possible to jump into the middle of a for loop or out of afinally clause. L (IST) [first [, last] list source code for the current file. without arguments, list 11 lines around the current line or continue the previous listing. with one argument, list 11 lines around und at that line. with two arguments, list the given range; if the second argument is less than the first, it is interpreted as a count. A (RGS) Print the argument list of the current function. P Expression Evaluate the expression in the current context and print its value. Note print can also be used, but is not a debugger command-This executes the python print statement. PP expression Like the p command, cannot the value of the expression is pretty-printed using the pprint module. Alias [name [command] Creates an alias called name that executes command. the command must not be enclosed in quotes. replaceable parameters can be indicated by % 1, % 2, and so on, while % * is replaced by all the parameters. if no command is given, the current alias for name is shown. if no arguments are given, all aliases are listed. aliases may be nested and can contain in anything that can be legally typed at the PDB prompt. note that internal PDB commands can be overridden by aliases. such a command is then hidden until the alias is removed. aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. as an example, here are two useful aliases (especially when placed in. pdbrc file): # print instance variables (usage "Pi classinst") alias Pi for K in % 1. _ dict __. keys (): Print "% 1. ", K," = ", % 1. _ dict _ [k] # print instance variables in selfalias ps pi self Unalias name Deletes the specified alias.[!] Statement Execute the (one-line) statement in the context of the current stack frame. the exclamation point can be omitted unless the first word of the statement resembles a debugger command. to set a global variable, You Can prefix the assignment command with a global command on the same line, e.g. :( PDB) Global list_options; list_options = ['-l'] (PDB) Run [ARGs...] Restart the debugged Python program. if an argument is supplied, it is split with "shlex" and the result is used as the new sys. argv. history, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run ". new in version 2.6. Q (uit) Quit from the debugger. The program being executed is aborted.

 

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.