Python runtime environment and exception handling

Source: Internet
Author: User

1. Python Startup

Command format for Python:

python [option] ... [-C cmd |-M mod | file |-] [Arg] ...
Options Describe
-j

Start a warning that some features will be removed or changed from Python3

-B
Prevent creating. PYc or. pyo Files on Import
-E Ignore environment variables
-H
Print a list of all available command-line options
-I.
Enter interactive mode after the program executes
-M module Run the Library module as a script
-O
Optimization mode
-oo
Optimization mode, deleting a document string when creating a. pyo file
-Q ARG

Specifies the behavior of the division operator in Pyhthon2, with a value of-qold (default),-qwarn,-qwarnall,

One of-qnew

-S
To prevent the user site Directory from being appended to Sys.path
-S
Block include site initial module
-T
Report on inconsistent label usage warnings
-tt
Taberror exception caused by inconsistent label usage
-U
unbuffered binary stdout and stdin
-U
Unicode literal, all string literals are processed in Unicode (only used in Python2)
-V
Verbose mode, tracking import statements

-V

Print version Information
-X
Skip the first line of the source program
-C cmd
Execute cmd as a string

2. Doctest Code Test Module

The Doctest module allows the embedding of annotations within a document string to show the expected behavior of various statements, especially the structure of functions and methods; The document string here looks like an interactive shell session, can be used to test whether the document is in sync with the main program, or to test the program itself based on the document.

Custom Test Module test.py:

[[email protected] home]# cat test.py #!/usr/bin/python3def Add (num1,num2): "' >>> Add (12,23) # ' >> > ' need to have a space after ' return num1+num2

Test using the Doctest module:

In [1]: Import Testin [2]: Import Doctestin [3]: Doctest.testmod (Test) #测试test. PY module Out[3]: TestResults (failed    =0, Attempted=1) in [4]: Doctest.testmod (test,verbose=true) trying:add (12,23) Expecting:35ok1 items had no tests: Test1 items passed all tests:1 tests in TEST.ADD1 tests in 2 Items.1 passed and 0 failed. Test passed. OUT[4]: TestResults (failed=0, attempted=1)

You can also define the self-test module directly:

[[Email protected] home]# cat test.py #!/usr/bin/python3def add (NUM1,NUM2):          '         >> > add (12,23)         35          '         return num1+num2if __name__ ==   ' __main__ ':        import doctest         doctest.testmod () [[email protected] home]# python3 test.py       #测试通过时不会显示任何信息 [[Email protected] home]# python3 test.py -v    #输出详细信息Trying:     add (12,23) expecting:    35ok1 items  had no tests:    __main__1 items passed all tests:    1 tests  in __main__.add1 tests in 2 items.1 passed and 0 failed. Test passed.

3. Python Exception handling

In some programming languages, errors are indicated by special function return values, while Python uses exceptions, which are code that executes only when an error occurs. Errors are usually: syntax errors and logical errors.

Syntax error: The software is structurally faulty and cannot be interpreted by the interpreter or compiled by the compiler.

Logic error: Due to incomplete or illegal input, it may be necessary for logic not to generate, calculate or output the result

The process cannot be performed, and so on.

In Python, an exception is an object that represents an error or an exception that is triggered when an error is detected. Python can pass an exception object through an abnormal conduction mechanism, sending out a signal that the exception occurs, and the programmer can trigger the exception manually in the code. Python exceptions can be understood as: the behavior of the programmer in the event of an error and beyond the normal flow of control. This treatment can be divided into two stages.

First stage: The interpreter triggers an exception, at which time the current program flow is interrupted;

Phase two: Exception handling, such as ignoring non-fatal errors, mitigating the effects of errors, etc.

The main functions of this approach are:

Error handling: Default processing, stopping programs, printing error messages, handling exceptions using try statements and recovering

Event notification: Used to emit valid status information

Special case handling: Unable to adjust code to handle the scene

Terminating behavior: The try/finally statement ensures that the necessary end-handling mechanism is executed

Unconventional control Flow: Exception is an advanced jump (goto) mechanism

    • Detection and processing of anomalies

In Python, exceptions are detected by a try statement, and any code in a try statement block is monitored to check for exceptions. In this article, Python3 is used as a demonstration.

There are two main types of try statements:

Try-except: Detects and handles exceptions. Multiple except can be used to support execution code with no probe exception using the ELSE clause

Try-finally: Detects only anomalies and does some necessary cleanup work. There can be only one finally.

Compound form of the Try statement: try-except-finally.

Try-except statement:

Try:try_suiteexcept Exception [as reason]: Except_suite in [1]: Try: ...: f1=open ('/tmp/a.txt ', ' R ') ...: Except IOError as e: ...: print (' Could nor open file ', E) ...: Could nor open file [Errno 2] No such file or D Irectory: '/tmp/a.txt '

Try-except-else statement:

There is no limit to the number of except clauses, but else only one; the ELSE clause executes when no exception occurs, and when there is no conforming except clause, the exception is passed up to the previous try in the program or to the top of the DAO program.

Try:try_suiteexcept Exception1 [as reason]: Suite_exception1except (Exception1, Exception2, Exception3 ...) [, reason]: Suite ... except:suiteelse:else_suite

Try-finally statement:

The FINALLY clause executes regardless of whether the exception occurs, and is often used to define the cleanup work that must be done, such as closing a file or disconnecting a service, and then continuing to throw an exception up one level after all the code in finally has finished executing.

Try:try_suitefinally:finally_suite

Try-except-else-finally statement:

Try:try_suiteexcept exception1:suite_exception1except (Exception1, Exception2,): Suite23...else:else_suite Finally:finally_suite
Clause form Description
Except
Catch all (other) exception types
Except name [as E]:
To catch only specific exceptions
Except (name1,name2):
To catch the exceptions listed

Else

Run if there is no exception
Finally
Always run this code block

4. Custom Exceptions

The Raise statement allows the programmer to force a specified exception to be thrown. Its syntax format is:

raise[someexception [, Arg [, Traceback]]

Someexception: The name of the exception, only strings, classes, or instances can be used;

Args: Arguments passed to the exception in the form of a tuple;

Traceback: Abnormal departure a newly generated trace record used for exception-normalization, which is used to re-throw an exception.

In [9]: try:   ...:     raise nameerror (' HiThere ')       #定义异常    ...: except nameerror:  &nbsp, .....:      print (' an except flew by! ')    ...:     raise                           # Trigger Exception    ...: an except flew by!--------------------------------------------- -----------------------------nameerror                                  Traceback  (most recent call last) <ipython-input-9-9448df11d518> in  <module> ()       1 Try:----> 2     raise nameerror (' hithere ')        3 except nameerror:      4     print (' an except flew by! ')       5     raisenameerror: hithere

Most of the standard exceptions are derived from Standerror, which have 3 abstract subclasses:

Arithmeticerror

Exception base class thrown due to arithmetic errors

Overflowerror , Zerodivisionerror , Floatingpointerror

lookuperror

EnvironmentError

Base class for exceptions caused by external causes

IOError , OSError , Windowserror

Custom Exception classes:

Custom exception classes are usually divided into two main categories:

Custom exceptions and multiple inheritance: multiple inheritance from defining exception classes and standard exception classes, for example:

Class Customattributeerror (Customexception,attributeerror):

Pass

Other exceptions used in the standard library: such as Arithmeticerror, Environmenterror, etc.

An Assert statement is typically used to reference debug code in a program, in the syntax format:

assert condition [, expression]

If the condition condition is met, assert does nothing, and if the condition is not met, assert instantiates the Assertionerror as a parameter and raises the result instance.

If you run Python with the-O optimization option, the Assert is an empty operation and the compiler does not generate code for the Assert statement. Run Python does not use the-o option, the __debug__ built-in variable is true, otherwise false.

The Assert statement is equivalent to the following code:

if  __debug__:    if not  condition :        raise  assertionerror, < Expression> 
In [17]: assert len ([' My boy ',]) >10     #条件len ([' My boy ', 12]) &GT;10 does not meet the legal default exception--------------------------------------------------------------------------assertionerror                             Traceback  (Most recent call last) < Ipython-input-17-cc0a09de885b> in <module> ()----> 1 assert len ([' my  Boy ', >10assertionerror: in [18]: assert range]) (4) ==[0,1,2,3]        #条件range (4) ==[0,1,2,3] Do not meet the default exception--------------------------------------------------------------------------assertionerror                             Traceback  (most recent call last) &LT;ipython-input-18-8b7aafe34e9e> in <module> ()----> 1 assert range (4) ==[ 0,1,2,3]assertionerror: in [19]: assert 1==1                          #条件满足, No output In [20]: assert range (4) ==[0,1,2,3],ioerror  #条件不满足, The custom exception is IOError--------------------------------------------------------------------------assertionerror                             Traceback  (Most recent call last) < Ipython-input-20-49011133d0d8> in <module> ()----> 1 assert range (4) ==[ 0,1,2,3],ioerrorassertionerror: <class  ' OSError ' >


This article is from the "Wind and Drift" blog, please be sure to keep this source http://yinsuifeng.blog.51cto.com/10173491/1922560

Python runtime environment and exception handling

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.