1. Scope
1.1 Scopes
Code 1
If 1 = = 1: name = ' Alex ' for I in range: name = iprint (name) # java/c# can not # Python/javascript can # Python No block-level scope in
Code Listing 2: Functions
def func (): name = ' Alex ' Print (name) def func (): name = ' Alex ' func () print (name) # Python with function as scope
Code Listing 3:
name = ' Alex ' def F1 (): print (name) def f2 (): name= ' Eric ' F1 () f2 () # Python scope before execution
Code Listing 4:
name = ' Alex ' def F1 (): print (name) def f2 (): name = ' Eric ' return F1ret = F2 () ret () # Python scope chain, from inside out, until you find to an error
Code Listing 5:
Li = [x+100 for x in range] if X>6]print (LI)
Code Listing 6:
Li = [lambda:x for x in range]]r = li[0] () print (R) # anatomy # li type: List # of elements in the Li list: [Functions, Functions, functions ...] # function before execution, internal code does not execute # LI[0],LAMBDA function # function (), execute function # return value: 9
Code Listing 7:
Li = []for i in range: def F1 (): return i li.append (F1) print (Li[0] ()) print (Li[1] ()) print (Li[2] ()) # Output result # 9# 9# 9li = []for i in range: def F1 (x=i): return x li.append (F1) print (Li[0] ()) print (Li[1] ()) Print (Li[2] ()) # output Result # 0# # 2
PS: Essentially see if the code executes
1.2 Summary
- No block-level scopes in Python
- Function-scoped in Python
- Python scope chain, from inside out, until an error is not found
- The scope of Python has been determined before execution
1.3 Python multiple Inheritance version 2.7 vs. 3.5
- All classes in Python 3 inherit object by default, which is called the new class
- Python 2 classes do not inherit object by default, which is called the classic class
2. Socketserver and IO multiplexing
2.1 Socketserver Basic Execution process
Import Socketserverclass MyClass (socketserver. Baserequesthandler): def handle (self): passobj = Socketserver. Threadingtcpserver ((' 127.0.0.1 ', 9999), MyClass) Obj.serve_forever ()# Create socket object # Accept processing Request # server_address = (' 127.0.0.1 ', 9999) # Requesthandlerclass = MyClass = = () # self. Requesthandlerclass () = MyClass () = = () # 1.obj encapsulates the self. Requesthandlerclass = myclass# 2. Created socket, bind, Lister
2.2 Real-many concurrency via IO multiplexing
Overview:
Io multiplexing does not consume CPU
Select,poll,epoll (supports all IO operations and does not support file operations)
Does the inside of the socket object change?
When does it change? Connect or send and receive messages
The server-side socket has changed to indicate a new connection
SK: There's a new connection coming up.
Conn: To send and receive messages.
IO multiplexing: Listen for changes inside the socket object
1) Multiple concurrent connection implementations
Server
Import Socketimport Selectsk = Socket.socket () sk.bind ((' 127.0.0.1 ', 999,)) Sk.listen (5) while True: rlist,w,e, = Select.select ([SK,], [], [], 1) #1为超时时间 print (rlist) # rlist in the Socket object list, [SK,] # has a new connection rlist = [SK] # no connection R List = [] for R in Rlist: print (R) conn, address = R.accept () conn.sendall (bytes (' Hello ', encoding= ' Utf-8 '))
Client
Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 999,)) data = SK.RECV (1024x768) print (data) while True: input ( ">>>") Sk.close ()
2) IO multiplexing implements pseudo concurrency and can send and receive messages
Server
Import Socketimport Selectsk = Socket.socket () sk.bind ((' 127.0.0.1 ', 999,)) Sk.listen (5) inputs = [Sk,]while True: Rlist,w,e, = select.select (inputs, [], [], 1) #1为超时时间 print (len (inputs), Len (rlist)) # Monitor SK ( Server-side) object, if the SK object changes, indicating that there is a client to connect, some time the rlist value is [SK] # Monitoring Conn Object, if the conn changes, indicating that the client has a new message sent over, some time the value of rlist is [client] # Rlist socket Object list, [SK,] # has a new connection rlist = [SK] # no connection rlist = []for R in Rlist: if r = = SK: # New customers to connect to conn, address = R.accept () # conn What is it? In fact it is also the socket object inputs.append (conn) Conn.sendall (bytes (' Hello ', encoding= ' Utf-8 ')) else: # Someone sent me a message. R.RECV (1024)
Client
Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 999,)) data = SK.RECV (1024x768) print (data) while True: INP = Input (">>>") sk.sendall (bytes (INP, encoding= ' Utf-8 ')) Sk.close ()
3) Read/write separation implementation
Server
Import Socketimport Selectsk = Socket.socket () sk.bind ((' 127.0.0.1 ', 9998,)) Sk.listen (5) inputs = [sk,]outputs = []while T Rue:rlist,wlist,e, = select.select (inputs, outputs, [], 1) #1为超时时间 print (len (inputs), Len (rlist), Len (wlist), Len (o utputs) # Listen to the SK (server side) object, if the SK object changes, indicating that there is a client to connect, some time the rlist value is [SK] # Monitoring Conn Object, if the conn changes, indicating that the client has a new message sent over, some time the value of rlist is [client] # rlist Socket Object list, [SK,] # has a new connection rlist = [SK] # no connection rlist = [] for r in rlist:if r = = SK: # New Guest User to connect conn, address = R.accept () # conn What is it? In fact it is also the socket object Inputs.append (conn) conn.sendall (bytes (' Hello ', encoding= ' utf-8 ')) Else: # Someone sent me a message Try:ret = R.RECV (1024x768) if not ret:raise excep tion (' Disconnected ') Else:outputs.append (R) except Exception as E:in Puts.remove (R) # All the people who sent me messages for W in Wlist:w.sendall (bytes (' response ', encoding= ' Utf-8 ')) #回复消息 Outputs.remove (w) # The person who deleted the reply message
Client
Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 9998,)) data = SK.RECV (1024x768) print (data) while True: INP = Input (">>>") sk.sendall (bytes (INP, encoding= ' Utf-8 ')) print (SK.RECV (1024x768)) Sk.close ()
4) Reply to Received message
Server
Import Socketimport Selectsk = Socket.socket () sk.bind ((' 127.0.0.1 ', 9998,)) Sk.listen (5) inputs = [sk,]outputs = [] Messages = {}# del Messages[alex] #删除alex的消息 # message = {# ALEX:[MSG1, MSG2,]# eric:[msg1, MSG2,]#}while True: Rlist,wlist,e, = select.select (inputs, outputs, [], 1) #1为超时时间 print (len (inputs), Len (rlist), Len (wlist), Len (output s) # Listen to the SK (server side) object, if the SK object changes, indicating that there is a client to connect, some time rlist value for [SK] # Monitoring Conn Object, if the conn changes, indicating that the client has a new message sent over, some time the value of rlist is [client] # RLI St Socket Object list, [SK,] # has a new connection rlist = [SK] # no connection rlist = [] for r in rlist:if r = = SK: # New customer to connect Conn, address = r.accept () # What is Conn? In fact, it is also the socket object Inputs.append (conn) messages[conn] = [] Conn.sendall (bytes (' Hello ', encoding = ' Utf-8 ') Else: # Someone sent me a message. Try:ret = R.RECV (1024x768) if not RET: Raise Exception (' disconnected ') Else:outputs.appEnd (R) messages[r].append (ret) except Exception as E:inputs.remove (R) Del Messages[r] # All the people who sent me messages for w in wlist:msg = Messages[w].pop () resp = msg + bytes (' Resp Onse ', encoding= ' Utf-8 ') W.sendall (resp) #回复消息 Outputs.remove (w) # Delete a reply message wlist
Client
Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 9998,)) data = SK.RECV (1024x768) print (data) while True: INP = Input (">>>") sk.sendall (bytes (INP, encoding= ' Utf-8 ')) print (SK.RECV (1024x768)) Sk.close ()
Thredingtcpserver Source Code Analysis
PS: All lookups should follow everything starting from the point of Origin
3rd Chapter process and thread
3.1 Multi-threaded multi-process
Overview:
1, an application, can have multi-process and multi-threading
2, Default: Single process, single thread
3, single process, multi-threaded
L IO operation, no CPU usage
Multithreading improves concurrency
• Computational operations, CPU usage
Multiple processes to improve concurrency
4, GIL, Global interpreter lock
Summary:
- Multithreaded multi-process for the purpose of providing concurrency
- IO-intensive: Multithreading
- COMPUTE-Intensive: multi-process
Ps:io operation, does not occupy CPU GIL, global interpreter lock
3.2 How to build multithreading
Practice creating the main thread, child threads
Import Threadingt = Threading. Thread (TARGET=F1, args= (123,)) T.start () #不代表当前纯种会被立即执行f1 (111) #主线程
Basic configuration Parameters
Import Threadingt = Threading. Thread (TARGET=F1, args= (123,)) T.setdaemon (True) # True, indicates that the main thread is not equal to this child thread T.start () # does not mean that the current purebred will be executed immediately t.join (5) # indicates the main thread to this point, Wait for ... until the child thread executes # parameter: Indicates the main thread waits up to the time n seconds # F1 (111) #主线程print (' End ') print (' End ') print (' End ')
ImportSocketserver
classMyClass(Socketserver. Baserequesthandler):
defHandle( Self):
Pass
# Create a Socket object
# Accept processing Requests
# server_address = (' 127.0.0.1 ', 9999)
# requesthandlerclass = MyClass = = ()
# Self. Requesthandlerclass () = MyClass () = = ()
# 1.obj encapsulates the self. Requesthandlerclass = MyClass
# 2. Created socket, bind, Lister
Obj= Socketserver. Threadingtcpserver ((' 127.0.0.1 ', 9999), MyClass)
Obj.serve_forever ()
Ten sockets (two)