Python Modules (eight) socketserver and threads, processes

Source: Internet
Author: User

Directory

    • Exception handling
    • Socketserver
    • threads, processes
First, exception handling


Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
code example:

 whiletrue:n1= Input ('input a number:') N2= Input ('input a number:')    Try: N1=Int (n1) N2=Int (n2) Res= n1 +N2Print(RES.SD) L= [1,2,3,4,]        Print(l[10]) d= {1:'a', 2:'b'}        Print(d[3])        Print('num:%s'%Res)exceptArithmeticerror as E:#Reference Property Error        Print('Arithmeticerror')    exceptIndexerror as E:#Subscript Error        Print('Indexerror')    exceptKeyerror as E:#Key Error        Print('Keyerror')    exceptValueError as E:#incorrect value for reference        Print('ValueError', E)exceptException as E:#throw most of the error        Print('exception Error')        Print(e)


By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.

#Custom Exceptionsclassdemoexception (Exception):def __init__(self,msg): Self.message=msgdef __str__(self):returnSelf.messagea= 1Try:    #throws an exception if the condition is not met    assertA = = 1exceptdemoexception as E:Print(e)Else:    Print('OK')#Whether or not an exception exists, the finally is executedfinally:    Print(' Over')
Second, Sokectserver


Socketserver is a high-level module in the standard library that simplifies the implementation of network clients and servers.
1. To implement this module, you must define a handler class that inherits from the base class Baserequesthandler. Instances of the Baserequesthandler class can implement the following methods:
1, H.handle () calls the method to perform the actual request operation. This function can be called without any arguments, but several instance variables contain useful values. H.request contains the request, H.client_address contains the client address, and H.server contains an instance of the calling handler. For data flow services such as TCP, the H.request property is a socket object. For a datagram service, it is a byte string that contains the data received.
2.h.setup () This method is called before handle (). By default, it does not take any action. If you want the server to implement more connection settings, you can do so here.
3.h.finish () Call this method to perform a purge operation after handle () is executed. If both setup () and handle () do not generate an exception, you do not need to call the method.
2. Server. To use a handler, you must insert it into the server object. Four basic server classes are defined.
1, TCPServer support the IPv4 TCP protocol server.
2, Udpserver support the IPv4 UDP protocol server.
3. Unixstreamserver uses UNIX domain sockets to implement a data flow protocol-oriented server, which is integrated from TCPServer.
4, unixdatagramserver inherit from Udpserver

Examples of four server classes have methods and variables:
1. S.socket socket object for incoming requests
2. S.server_address the address of the listener server
3. S.requesthandleclass the request handler class passed to the server constructor and supplied by the user
4, S.server_forever () processing the wireless request
5, S.shutdown () Stop Server_forever () loop
6, S.fileno () returns the integer file descriptor of the server socket. This method can be effectively used to poll the operation instance

Code instance

Server Side#Import the moduleImportSocketserver#defines a class that inherits Socketserver. BaserequesthandlerclassServer (socketserver. Baserequesthandler):defhandle (self):#Print client address and port        Print('New Connection:', self.client_address)#Loops         whileTrue:#receive data sent by customersdata = SELF.REQUEST.RECV (1024)            if  notData Break#if the received data is empty, jump out, otherwise print            Print('Client Data:', Data.decode ()) self.request.send (data)#Send the received message back to the clientif __name__=='__main__ ':Host,port ='127.0.0.1 ', 8080 #定义服务器地址和端口Server = Socketserver. Threadingtcpserver ((host,port), Server)#enables multi-threaded socket callsServer.serve_forever ()#does not appear after the end of a client, the current server side will be closed or error, but continue to run, and other clients continue to call. Client SideImportSocketip_port= ('127.0.0.1', 8080) SK=Socket.socket () sk.connect (Ip_port) whileTrue:raw= Input ('>>'). Strip () sk.send (bytes (Raw,'UTF8')) msg= SK.RECV (1024)    Print(Str (MSG,'UTF8') ) Sk.close ()


Iii. Processes and Threads



1. Definition
A process is a program with a certain set of independent functions, about one run activity on a data collection. A process is an independent unit of system resource allocation and scheduling.
A thread is an entity of a process that is the basic unit of CPU scheduling and allocation, which is a smaller unit that can run independently than a process. Threads do not own system resources, but they can contribute all of the resources owned by the process to other threads that belong to one process.
2. Relationship
One thread can create and destroy another thread, and can execute concurrently between multiple threads in the same process.
3, the biggest difference is that they are different resource management methods. The process has a separate address space, and after a process crashes, it does not affect other processes, and the thread is just a different execution path in a process. Threads have their own stacks and local variables, but no separate address space. So a thread dies equals the entire process dies, and many processes are stronger than multithreaded programs, but the process switches are expensive. For some concurrent operations that require co-workers to share certain variables, only threads can be used, and processes cannot be used.
Python Threading Module
Threading provides a higher-level API than the thread module to provide the concurrency of threads. These threads run concurrently and share memory.
First, the use of thread
The target function can instantiate a thread object, each of which represents a threaded object that can be run through the start () method.
There are two ways to create a thread: One is to override its run method by inheriting the thread class, and the other is to create a threading. The thread object in which the callable object is passed in as a parameter in its initialization function (__INIT__).

ImportThreadingImport Timedefsayhi (num):Print('running on nuber:%s'%num) time.sleep (3)if __name__=='__main__': T1= Threading. Thread (target=sayhi,args= (1,)) T2= Threading. Thread (target=sayhi,args= (2,)) T1.start () T2.start ( )Print(T1.getname ())Print(T2.getname ())ImportThreadingImport Timedefsayhi (num):Print('running on nuber:%s'%num) time.sleep (3)if __name__=='__main__ ':T_list = []     forIinchRange (20): T= Threading. Thread (target=sayhi,args=[I,]) T.start () t_list.append (t) forIinchT_list:i.join ()Print('----done--')


Join functions in the threading module
The function is primarily to block the process until the thread finishes executing. The common practice is to start a batch of threads, and finally join these threads to the end.
The principle is to verify that the thread in the thread pool is finished, that it does not end, that the thread ends, and if it ends, jumps to the next thread's join function.




End

Python Modules (eight) socketserver and threads, processes

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.