Debugging of Python Automation

Source: Internet
Author: User

# # # #调试

# # # #查看日志与断言

‘‘‘

Throws an exception using the Raise statement. In the code, the Raise statement contains the following sections:

(1) Raise keywords;

(2) The invocation of the exception function;

(3) A string passed to the exception function, containing useful error messages

‘‘‘

########################################## #抛出异常 ####################################

def boxprint (symbol,width,height):

If Len (symbol)!=1:

Raise Exception (' Symbol must is a single character string. ')

If width<=2:

Raise Exception (' Width must be greater than 2. ')

If height<=2:

Raise Exception (' Height must be greater than 2. ')

Print (Symbol*width)

For I in Range (height-2):

Print (symbol+ ("* (width-2)) +symbol)

Print (Symbol*width)

For Sym,w,h in ((' * ', + +), (' 0 ', 20,5), (' X ', 1,3), (' ZZ ', 3, 3)):

Try

Boxprint (SYM,W,H)

Except Exception as err:

Print (' An exception happened: ' +str (ERR))

###################################### #取得反向跟踪的字符串 ####################################

‘‘‘

The reverse trace contains the error message, the line number of the code that caused the error, and causes the

The sequence of the wrong function call. This sequence is called the "Call stack"

‘‘‘

‘‘‘

Call Traceback.format_exc () to get the string form that throws the exception.

You can write the reverse trace information to a log file and let the program continue to run

‘‘‘

Import Traceback

Try

Raise Exception (' This is the error message. ')

Except

Errorfile=open (' ErrorInfo.txt ', ' W ')

Errorfile.write (Traceback.former_exc ())

Errorfile.close ()

Print (' The Traceback info is written to errorInfo.txt. ')

###################################### #断言 ####################################

‘‘‘

"Assertion" is a sanity check that ensures that the code does not do anything that is obviously wrong.

These sanity checks are performed by the Assert statement. If the check fails, an exception is thrown

The Assert statement contains the following sections:

(1) Assert keyword;

(2) conditions (that is, evaluation of the value);

(3) comma;

(4) The string to display when the condition is false

‘‘‘

podbaydoorstatus= ' Open '

Assert podbaydoorstatus== ' open ', ' The pod bay doors need to be ' open '. '

podbaydoorstatus= ' i \ ' m sorry,dave.i \ ' m afraid I can\ ' t do that. '

Assert podbaydoorstatus== ' open ', ' The pod bay doors need to be ' open '. '

###################################### #禁用断言 #######################################

‘‘‘

You can disable assertions by passing in the-o option when you run Python

‘‘‘

###################################### #日志 ###########################################

‘‘‘

Python's logging module makes it easy to create custom message records.

These log messages will describe when the program executes when the log function call is reached,

Lists the value of any variable you specify at the time.

On the other hand, missing log information indicates that some of the code has been skipped and never executed

‘‘‘

###################################### #使用日志模块 ###################################

‘‘‘

To enable the logging module, display the log information on the screen while the program is running,

Please copy the following code to the top of the program (but below the #! line in Python)

‘‘‘

Import logging

Logging.basicconfig (level=logging. debug,format= '% (asctime) s-% (levelname) s-% (message) s ')

‘‘‘

When Python logs a log of an event, it creates a LogRecord object that holds information about the event.

The function of the logging module allows you to specify the details of the LogRecord object you want to see, as well as the details of the desired display.

Way.

‘‘‘

Import logging

Logging.basicconfig (level=logging. debug,format= '% (asctime) s-% (levelname) s-% (message) s ')

Logging.debug (' Start of Program ')

def factorial (n):

Logging.debug (' Start of factorial (%s%%) '% (n))

Total=1

For I in Range (n+1):

Total*=i

Logging.debug (' I am ' +str (i) + ', Total was ' +str (total))

Logging.debug (' End of factorial (%s%%) '% (n))

Print (factorial (5))

Logging.debug (' End of Program ')

‘‘‘

The Logging.debug () call not only prints the string passed to it, but also contains a timestamp and word debug

‘‘‘

###################################### #不要用print () Debug ###################################

‘‘‘

1, each clear print () call, may delete the log message is not used to generate

2, log message benefits: You can arbitrarily in the program to add as much as you want, later

Just add one logging.disable (logging. CRITICAL) is called, you can suppress the log

‘‘‘

###################################### #日志级别 ###################################

‘‘‘

Log levels in Python (from least important to most important)

Level log Function description

DEBUG Logging.debug () the lowest level. Used in small details, usually only when diagnosing a problem, will you care about these messages

INFO Logging.info () is used to log messages for general events in the program, or to confirm that everything is working properly

WARNING logging.warning () is used to indicate a possible problem that does not prevent the program from working, but may

Error Logging.error () is used to log errors, which causes the program to fail to do something

CRITICAL logging.critical () highest level. Used to indicate a fatal error, which causes or will cause the program to stop working completely

‘‘‘

‘‘‘

The benefit of logging levels is that you can change the priority of the log messages you want to see

Pass in logging to the Basicconfig () function. DEBUG, all log-level messages will be displayed

Incoming Logging.error, only error and critical messages are displayed, debug, info, and warning messages are skipped

‘‘‘

###################################### #禁用日志 ###################################

‘‘‘

The logging.disable () function disables log information as long as a log level is passed to logging.disable ()

It disables all log messages for that level and lower level. If you want to disable all logs, simply

Add logging.disable (logging. CRITICAL)

‘‘‘

Import logging

Logging.basicconfig (level=logging.info,format= '% (asctime) s-% (levelname) s-% (message) s ')

Logging.critical (' Critical error! Critical error! ')

Logging.disable (logging. CRITICAL)

Logging.critical (' Critical error! Critical error! ')

Logging.error (' error! error! ')

################################# #将日志记录到文件 ###################################

Import logging

Logging.basicconfig (filename= ' myProgramLog.txt ', level=logging. debug,format= '% (asctime) s-% (levelname) s-% (message) s ')

################################# #调试 ###################################

‘‘‘

GO, Step, over, out, Quit:

The Step button lets the debugger enter the function call

The over button quickly executes a function call without stepping into it

The Out button executes the rest of the code quickly until it is out of the current function

Go: The debugger stops at the end of the program or at a breakpoint

‘‘‘

‘‘‘

Write an Assert statement, and if the variable spam is an integer less than 10, it triggers assertionerror

1, assert (spam>=10, ' The spam variable is less than 10. ')

Write an Assert statement that triggers assertionerror if eggs and bacon contain the same string and are case-insensitive

2. Assert (Eggs.lower ()!=bacon.lower (), ' The eggs and bacon variables are the same! ')

Write Assert statement, always trigger Assertionerror

3, assert (False, ' This assertion always triggers. ')

‘‘‘

Debugging of Python Automation

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.