Python base try exception handling, socket socket base Part1

Source: Internet
Author: User
Tags assert throw exception ssh example

Exception handling

Error

Errors in the program are generally divided into two types:

1, syntax error, this error, can not get through the Python interpreter syntax detection, must be corrected before the program execution

2, logic errors, human-caused errors, such as data type errors, call method errors, and so on, these interpreters will not be detected, only in the process of execution can throw the error

Abnormal

An exception is information thrown by the Python interpreter when it encounters an error while running the program, such as:

Python Exception type:

Common exceptions:

1 Attributeerror     attempt to access an object that does not have a tree, such as foo.x, but Foo has no attribute x 2 IOError     input/output exception; it is basically unable to open file 3 Importerror     cannot introduce module or package Basically a path problem or name error 4 indentationerror     syntax error (subclass); Code is not aligned correctly 5 Indexerror subscript index is     out of sequence boundary, for example, when X has three elements, but tries to access X[5] 6 keyerror     attempting to access keys that do not exist in the dictionary 7 keyboardinterrupt     CTRL + C is pressed 8 nameerror     use a variable that has not been assigned to the object 9 syntaxerror     python code is illegal, the code can not compile (personally think this is a grammatical error, write wrong) ten TypeError     The incoming object type does not conform to the requirement. Unboundlocalerror     attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it. ValueError     Pass in a value that is not expected by the caller, even if the value is of the correct type

Other Exceptions:

Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror Other exceptions
Other Exceptions

Exception handling

By default (non-programmers use raise-triggered exceptions), the executing program terminates the run of the program when it encounters an error throw exception, and the subsequent code does not continue to execute when the error point is interrupted.

Exception handling refers to the exception capture through the specified code, when snapping to the specified exception class into a specific logic to continue execution, so that the program will not be interrupted at the error point, generally used to catch the program can not control the exception of the error (such as the client abnormal interruption and server-side connection caused a server-side crash).

If-judging exception handling

The process of input detection and prevention of grammatical errors is controlled by logical judgment, but this kind of if judgment is not related to the original logic, so it can cause poor code readability.

Try...except ... Exception handling

A python-customized exception handling class with the following syntax:

1 try:2     code block 3 except exception type: 4     If an exception is detected in a try, the logic of this position is executed if the exception is the same as the except marked exception

Example 1: iterator stopiteration exception handling

Prepare file A.txt, only five elements

1111111222222222222333333334444555555555

Exception throw: Because the iterator F does not have so much content, the sixth __next__ throws a Stopiteration exception hint

1 f=open (' a.txt ', ' R ') 2 print (f.__next__ ()) 3 print (f.__next__ ()) 4 print (f.__next__ ()) 5 print (f.__next__ ()) 6 print (f._ _next__ ()) 7 print (f.__next__ ()) 8 print (f.__next__ ()) 9 print (f.__next__ ())

Exception handling: When the sixth __next__ throws an exception, except is more unusual, and if it is the same, close the file object

1 f=open (' a.txt ', ' R ') 2 try:3     print (f.__next__ ()) 4     print (f.__next__ ()) 5     print (f.__next__ ()) 6     Print (f.__next__ ()) 7     print (f.__next__ ()) 8     print (f.__next__ ()) 9     print (f.__next__ ())     print (f._ _NEXT__ ()) except stopiteration: #只能够捕捉处理指定的StopIteration异常, if the other exception is not processed, the error will still be thrown in the     f.close ()

Example 2: Multi-branch exception handling, multiple exception classes may appear in the code snippet, and a except can specify only one exception, so the multi-branch structure

1 s= ' asdf ' 2 l=[' a '] 3 d={' name ': ' Bob '} 4 try:5     # int (s)    #ValueError 6     # L[2]      #IndexError 7     d[' AG E ']    #KeyError 8 except Indexerror as E: #as E to assign the exception value of the captured Indexerror error message to E 9     print (e) except Keyerror as e:11< C16/>print (e) except ValueError as E:13     print (e)

Example 3: Universal exception, Exception, he can catch arbitrary exceptions

1 s= ' asdf ' 2 l=[' a ']3 d={' name ': ' Bob '}4 try:5     int (s)    #ValueError6     l[2]      #IndexError7     d[' age ']    #KeyError8 except Exception as E:9     print (e)

Note: If the requirement is a one-piece logical processing for all exceptions, then using a universal exception, if there are different processing logic for different exceptions, then using multi-branch structure, the end of the multi-branching structure can be followed by a Universal exception processing branch

Example 4: Additional Options for exceptions

1 s= ' asdf ' 2 l=[' a '] 3 d={' name ': ' Bob '} 4 try:5     int (s)    #ValueError 6     l[2]      #IndexError 7     d[' age ']
    #KeyError 8 except Exception as E:9     print (e) else:11     print (' Try code block without exception ' execute me ') finally:13     

Example 5: Proactively triggering an exception, artificially generating an exception

1 try:2     Raise TypeError (' type error ')    #类型错误是所触发的异常的值3 except Exception as E:4     print (e) 5 6 output Result: 7 type Error

Example 6: Custom Exception Handling Class

1 class Defaultexception (baseexception): 2     def __init__ (self,msg): 3         self.msg=msg4     def __str__ (self):  #定义类本身的返回值5         return self.msg6 try:7     raise Defaultexception (' type error ') 8 except defaultexception as E:9     print (e)    #DefaultException的返回值

Example 7: Assertion, similar to if judgment, but assertion is absolute true, if not true it will not execute down

1 a=12 b=23 assert a<b4 print (a+b)    #输出结果35 assert a>b    #输出结果: Assertionerror exception error 6 print (b-a)    #没执行

Example 8:try and if, if it is an if, requires each input to make a judgment, and try can do all the input processing

1 try:2     num1=input (' >>: ') 3     int (NUM1) #正统程序放到了这里, the rest belongs to exception handling category 4     num2=input (' >>: ') 5     int (num2) 6     num3=input (' >>: ') 7     int (NUM3) 8 except ValueError as E:9     print (e)

Use try: Except the way (but don't forget if)

1: Separate the error handling from the real work

2: Code easier to organize, clearer, complex tasks easier to implement;

3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed;

Only if some anomalies can not be predicted, it should be added try...except, other logic errors should be corrected as far as possible, avoid using exception handling

Socket Basics

C/S architecture

That is, the client/server architecture, B/S architecture (browsers/servers) also belong to the C/s architecture.

Socket socket is to complete the development of C/s architecture software.

Basics of Socket Foundation

The socket relies on the network, so the network foundation can't forget

Socket INTRODUCTION

In Python, the socket layer is located in the middle layer of the transport and application tiers of the TCP/IP stack and is a software abstraction layer that provides an up-down interface.

The socket encapsulates the TCP and UDP protocols, so programs written in the socket syntax follow the TCP and UDP protocols.

Note: The SOCKET=IP+PORT,IP is used to identify the location of the host in the network, port is used to identify the host's application, so ip+port can identify the only application in the Internet, so that the socket is actually a combination of IP and port

Socket category

Network programming only need to pay attention to af_inet, this is the most widely used, if the IPv6 platform needs to use AF_INET6.

Other: Af_unix, for UNIX file system communication, there are many other platforms used, not much to say

Socket Communication principle

The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), and calls the accept block, waiting for the client to connect.

The client initializes a Socket and then connects to the server (connect), and if the server side is properly accessed, the server end is blocked and the connection is successful, then the client-server connection is established.

The client sends a data request, the server receives the request and processes the request, and the server sends the response data to the client, the client reads the data, and loops.

The last client or server closes the connection and ends the interaction at the end.

Socket module

One-time socket communication (based on the local loopback address), which is explained by the process of calling

Service side:

Import Sockets=socket.socket (Socket.af_inet,socket. SOCK_STREAM) #买手机s. Bind ((' 127.0.0.1 ', 9000)) #手机插卡, if the tuple is (", 9000) represents all of the network cards, equivalent to 0.0.0.0s.listen (5)     #手机待机, The value in parentheses is the optimized conn,addr=s.accept () #手机接电话print for the TCP connection (            '%addr[0 from the phone ' from%s ') Msg=conn.recv (1024x768)             #听消息, Obedient Print (Msg,type (msg)) Conn.send (Msg.upper ())          #发消息, Speak Conn.close ()                    #挂电话s. Close ()                       #手机关机

Client:

Import Sockets=socket.socket (Socket.af_inet,socket. SOCK_STREAM)    #买手机s. CONNECT_EX ((' 127.0.0.1 ', 9000))           #拨电话s. Send (' NB '. Encode (' Utf-8 '))         #发消息, Speak ( can only send byte types) feedback=s.recv (1024x768)               #收消息, obedient print (Feedback.decode (' Utf-8 ')) s.close ()                                       #挂电话

Execution executes the server first and then executes the client.

Correlation Value Description:

1 Socket.socket (socket_family,socket_type,protocal=0) 2 socket_family can be Af_unix or Af_inet3 Socket_type can be SOCK_ STREAM (reliable connection-oriented data transfer, TCP protocol) or SOCK_DGRAM (non-connected unreliable data transfer, UDP) 4 protocol generally not filled, the default value is 0

Related method Description:

1 Service End Socket function 2 S.bind ()    binding (host, port number) to Socket 3 S.listen ()  start TCP Listener 4 s.accept ()  passively accept TCP Client connection, (blocked) wait for connection arrival 5  6 Client socket Function 7 S.connect ()     actively initializes an extended version of the TCP server Connection 8 S.CONNECT_EX ()  connect () function, returns an error code when an error occurs, instead of throwing an exception 9 10 socket function for public use 11 S.RECV ()            receives TCP data S.send () sends TCP data (send data is            lost when the amount of data to be sent is greater than the remaining space in the buffer cache), and the         full TCP data is sent by S.sendall () ( The essence is circular call Send,sendall in the amount of data to be sent is greater than the left buffer space, the data is not lost, loop call send until the end of the S.recvfrom ()        receive UDP data () s.sendto ()          Send UDP data s.getpeername ()     Connect to the far end of the current socket S.getsockname () address of the     current socket s.getsockopt ()      returns the parameter 19 of the specified socket S.setsockopt ()      sets the parameter of the specified socket S.close ()           close socket 21 22 lock-oriented socket Method s.setblocking ()     sets the blocking and non-blocking mode for sockets 24 S.settimeout ()      set timeout for blocking socket operation S.gettimeout ()      get blocked socket operation Timeout 26 27 function for file-oriented sockets S.fileno ()          Socket file Descriptor S.makefile ()        creates a file associated with the socket

Socket loop communication, that is, a connection to the continuous cycle of interaction, there are multiple connection request connection if the first connection is not interrupted, you can not connect, when the first connection is interrupted, the second one is connected, in turn

Server-side:

1 Import Socket 2 S=socket.socket (socket.af_inet,socket. SOCK_STREAM) #买手机 3 S.bind ((' 127.0.0.1 ', 9000)) #手机插卡 4 S.listen (5)     #手机待机, the values in parentheses are optimized for TCP connections 5 while True: #可以不停的接电话, That is, the connection is continuously accepted 6     conn,addr=s.accept ()            #手机接电话 7     print (' Call from%s '%addr[0]) 8 while     True:  #循环的收发消息 9         Msg=conn.recv (1024x768)             #听消息, obedient ten         print (Msg,type (msg))         Conn.send (Msg.upper ())          #发消息, talk 12     conn.close ()                    #挂电话13 s.close ()                       #手机关机

Client:

Import Sockets=socket.socket (Socket.af_inet,socket. SOCK_STREAM) #买手机s. Connect ((' 127.0.0.1 ', 9000)) #拨号while True: #通讯循环    msg=input (' >>: '). Strip ()    if not Msg:continue    s.send (Msg.encode (' Utf-8 '))    server_res=s.recv (1024x768)    print (' Server_res: ', Server_ Res.decode (' Utf-8 ')) Phone_client.close ()

Error handling:

Because the service side still exists four times the time_wait state of the wave in the Occupy address (if not understand, please delve into 1.tcp three times handshake, four waves wave 2.syn flood attack 3.) high-level Time_wait state optimization method in case of higher server concurrency

Solve

1 # Add a socket configuration to reuse IP and ports 2 phone=socket (af_inet,sock_stream)3# that 's it, plus 4 in front of bind  Phone.bind ('127.0.0.1', 8080)
Windows
/etc/= 1= 1= 1=/sbin/sysctl-= 1= 1 means turn on reuse. Allow time-= 1 To turnon fast recycling of time-WAIT sockets in TCP connections, which by default is 0, indicates off. Net.ipv4.tcp_fin_timeout Modify the default timeout time for Linux
Linux

Simple SSH Example

Service side

1 Import Socket 2 Import subprocess 3 Ssh_server=socket.socket (socket.af_inet,socket. SOCK_STREAM)   #生成socket实例对象 4 ssh_server.setsockopt (socket). Sol_socket,socket. so_reuseaddr,1) #重用地址 to prevent the use of 5 ssh_server.bind ((' 127.0.0.1 ', 8080)) 6 Ssh_server.listen (5) 7 print (' Server run ... ') 8 while True:9     conn,client_addr=ssh_server.accept ()  #循环等待连接10     print (' client: ', client_addr) one while     True: # Communication cycle         try:13             cmd=conn.recv (1024x768) #收消息14             res=subprocess. Popen (Cmd.decode (' Utf-8 '),       #执行命令15                              shell=true,16                              stdout=subprocess. pipe,17                              stderr=subprocess. PIPE)             stdout=res.stdout.read ()    #标准输出19             stderr=res.stderr.read ()    #标准输入20             std=stdout+ Stderr21             conn.sendall (STD)         except exception:24             break25     conn.close ()    #断连接, Go to Next Connection wait ssh_server.close () #关闭程序

Client:

1 Import Socket 2 Ssh_client=socket.socket (socket.af_inet,socket. SOCK_STREAM) 3 Ssh_client.connect ((' 127.0.0.1 ', 8080)) 4 while True: #通讯循环 5     cmd=input (' >>: '). Strip () 6     If not cmd:continue 7     ssh_client.send (Cmd.encode (' Utf-8 ')) 8     cmd_res = SSH_CLIENT.RECV (1024x768) 9     print (cmd_ Res.decode (' GBK ')) #windows10     # Print (Cmd_res.decode (' Utf-8 ')) #linux11 Ssh_client.close ()

Python base try exception handling, socket socket base Part1

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.