Python network programming day-1[exception handling, socket]

Source: Internet
Author: User

Exception handling:

Error:

1. Syntax error: The program run detects that a syntax error is thrown directly and terminates the program run.

2. Logic Error: The program encountered a logic error in the run, the system will ask the program to handle the exception, the program does not handle the system will throw an exception, and terminate the program run.

Abnormal:

Errors that occur during program run.

The exception is divided into three parts:

Trace information, exception class, outliers.

 n = input ( " >>>:   " ). Strip () s  = n + 1print   (s) execution result: D:\Python\Python36  -32\python.exe E:/python/day-23/day23.py  >>>: 1traceback (most recent call last): File /span> " e:/python/day-23/day23.py   ", line 7, in  <module> <----tracking information  s  = n + 1typeerror:must be str,  not   int exception class Exception value process finished with exit code  1 
Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input / output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access x[5]keyerror Attempting to access a key that does not exist in the dictionary keyboardinterrupt Ctrl+c is pressed nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements 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 a value that the caller does not expect , even if the type of the value is correct
Common Exceptions

How to handle Exceptions:

1.if processing: Handling errors before they occur, preventing errors from occurring

2. Try processing: Post-error processing, catching exceptions for processing

Use of Try:

When a try contains multiple exceptions, the first exception is thrown out of the code execution in the try to match the except exception handling.

Use the try and except to wrap the code that may be wrong, and use except to specify the type of error that is captured as follows:

Try :     = Input ("). Strip ()    = n + 1    print(s)except  TypeError:    print('-------------') execution Result: D : \python\python36-32\python.exe e:/python/day-23/day23.py>>>: 1-------------  Process finished with exit code 0

Support for Branch catch exceptions like if elif

ELSE: Executes the command following else when the code inside the try does not have an exception.

Finally: executes regardless of whether the code in the try has an exception

S1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)#except Exception as E:#print (e)Else:    Print('execute My code block without exception in try')finally:    Print('The module is executed whether it is unusual or not, usually for cleanup work')

To actively throw an exception (raise):

An error that throws a specified type on its own.

Try :     = Input ("). Strip ()    = Int (n) + 1    raise  TypeError except TypeError:     Print ('----raise throws the Type Error---------') execution result: D:\Python\Python36-32\ Python.exe e:/python/day-23/day23.py>>>: 1----raise the Type Error thrown---------  Process finished with exit code 0

Custom Exception classes:

class Ldslyerror (baseexception):   #定义错误类型的名字, Inherit baseexception    def__init__(self, msg):        self.msg=msgtry:    raise ldslyerror ('  Test')except  ldslyerror as E:    print(e)

Socket

Client/server-side architecture

That is, the C/s architecture. The program is divided into two parts, the client and the server side, the client sends the request to the service side, the service side responds the corresponding information to the client. Connect the client and the service side through the network.

Where is the socket on the computer:

The workflow of the socket:

Write and read form loops, called communication loops.

A simple client sends a command, the server executes the command and returns the execution result of the command:

#服务端
ImportSocketImportSubprocessserver= Socket.socket (socket.af_inet,socket. SOCK_STREAM)#Build ServicesServer.bind (('127.0.0.1', 8080))#listening for IP and portsServer.listen (5)Print('Server Run .....') whiletrue:conn,client_addr=server.accept ()#wait for client connection to establish connection object Conn Print(CLIENT_ADDR)#Print Client connection information whileTrue:Try: Client_msg= CONN.RECV (1024)#receiving client Messagesres = subprocess. Popen (Client_msg.decode ('Utf-8'), shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) stdout=res.stdout.read () stderr=Res.stderr.read () Conn.sendall (stdout+stderr)Print(Client_msg.decode ('Utf-8'))#Print Client Messages #conn.send (' Hi '. Encode (' Utf-8 ')) #发送给客户端消息 exceptException: Breakconn.close ()#Close Connectionserver.close ()#Close Service
#ClientImportsocketclient= Socket.socket (socket.af_inet,socket. SOCK_STREAM)#Establish clientClient.connect (('192.168.16.108', 8080))#IP address and port on client connection server whileTrue:cmd= Input ('>>>:'). Strip ()if  notCmd: Breakclient.send (Cmd.encode ('Utf-8'))#sending information to the service endserver_msg= CLIENT.RECV (1024)#receiving a reply from the server    Print(Server_msg.decode ('GBK'))#Print Service-side informationclient.close ()#Close Connection

Python network programming day-1[exception handling, socket]

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.