Tag: Address name cannot be maximum basename back module Erer application
One, isinstance (obj, CLS)
Checks if obj is an object of class CLS
Class Foo (object): Pass obj = foo () isinstance (obj, foo)
Second, Issubclass (sub, super)
Check if the sub class is a derived class of super class
Class Foo (object): Pass class Bar (foo): pass Issubclass (bar, foo)
Third, exception handling
1. Abnormal Foundation
In the programming process in order to increase the friendliness of the program in the event of a bug will not be displayed to the user error message, but the reality of a hint of the page, popular is not to let users see the big Yellow Pages!!!
- Try
- Pass
- Except Exception,ex:
- Pass
2. Abnormal type
There are so many exceptions in Python that each exception is dedicated to handling an exception!!!
1 Attributeerror attempt to access an object that does not have a tree, such as foo.x, but Foo does not have attribute x 2 IOError input/output exception; it is basically unable to open file 3 Importerror cannot introduce module or package; Basically path problem or name error 4 Indentationerror syntax error (subclass); Code not aligned correctly 5 Indexerror index is out of sequence boundary, for example, when X has three elements, but tries to access X[5] 6 Keyerror tries to access a key that does 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 has not yet been set, basically because there is another global variable with the same name, and 12 causes you to think that you are accessing it. ValueError Pass in a value that the caller does not expect, Even if the type of the value is correct
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:
- S1 = ' Hello '
- Try
- Int (S1)
- Except Exception,e:
- Print E
Next you may ask, since there is this universal exception, the other exception is not can be ignored!
A: Of course not, exceptions for special handling or reminders need to be defined first, and finally defined exception to ensure that the program runs correctly.
- S1 = ' Hello '
- Try
- Int (S1)
- Except Keyerror,e:
- print ' key error '
- Except Indexerror,e:
- print ' Index error '
- Except Exception, E:
- print ' ERROR '
3, abnormal other structure
1 try:2 # Main code block 3 pass 4 except Keyerror,e:5 # exception, execute the Block 6 pass 7 else:8 # The main code block executes, executes the Block 9 PASS10 Finally:11 # No matter if it's abnormal or not, finally execute the block Pass
4. Active Trigger exception
- Try
- Raise Exception (' wrong ... ‘)
- Except Exception,e:
- Print E
5. Custom Exceptions
Class Wupeiqiexception (Exception): def __init__ (self, msg): self.message = msg def __str__ (self): Return self.message try: raise Wupeiqiexception (' my exception ') except Wupeiqiexception,e: print E
6. Assertion
# Assert condition
Assert 1 = = 1
Assert 1 = = 2
Iv. Reflection
The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.
Class Foo (object): def __init__ (self): self.name = ' Wupeiqi ' def func: return ' func ' obj = Foo () # # # # # # # # # # # # # # # # # # # # # # # # # #hasattr (obj, ' name ') # # # # # # # # # # #getattr (obj, ' name ') getattr (obj, ' func ') # # # # # # # # Hasattr Set member # # # #setattr (obj, ' age ', setattr) (obj, ' show ', Lambda Num:num + 1) # # # # # # # # # # # # # # #delattr (obj, ' name ') delattr (obj , ' func ')
--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- -----------------
Socket
I. Overview
Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.
Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)
The difference between a socket and file:
- The file module is "open", "Read and write" "Close" for a specified document
- The socket module is "open", "Read and write" "Off" for server-side and client sockets
Web Service Applications:
#!/usr/bin/env python#coding:utf-8import Socket def handle_request (client): buf = Client.recv (1024x768) Client.send ("http/1.1 ok\r\n\r\n") client.send ("Hello, World") def Main (): sock = Socket.socket (socket.af _inet, Socket. SOCK_STREAM) sock.bind ((' localhost ', 8080)) Sock.listen (5) while True: connection, address = Sock.accept () handle_request (connection) connection.close () if __name__ = = ' __main__ ': Main ()
Second, explain
SK = Socket.socket (socket.af_inet,socket. sock_stream,0)
Parameter one: Address cluster
Socket.af_inet IPv4 (default)
Socket.af_inet6 IPV6
Socket.af_unix can only be used for single UNIX system interprocess communication
Parameter two: type
Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP
Socket. Sock_raw the original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_ The HDRINCL socket option constructs an IP header by the user.
Socket. SOCK_RDM is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.
Socket. Sock_seqpacket Reliable Continuous Packet service
Parameter three: protocol
0 (default) protocol related to a particular address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.
Import Socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket (socket.af_inet,socket. sock_dgram,0) Sk.bind (ip_port) while True: data = SK.RECV (1024x768) print DataImport socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket (socket.af_inet,socket. sock_dgram,0) while True: INP = raw_input (' data: '). Strip () if InP = = ' exit ': Break Sk.sendto (inp,ip_ Port) Sk.close ()
Sk.bind (Address)
S.bind binds the socket to the address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port).
Sk.listen (Backlog)
Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected.
The backlog equals 5, indicating that the kernel has received a connection request, but the server has not yet called the accept to process the maximum number of connections is 5
This value cannot be infinitely large because the connection queue is maintained in the kernel
Sk.setblocking (BOOL)
Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.
Sk.accept ()
Accepts the connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.
Incoming TCP Client connection (blocked) waiting for connection
Sk.connect (Address)
The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.
SK.CONNECT_EX (Address)
Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061
Sk.close ()
Close socket
SK.RECV (Bufsize[,flag])
Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.
Sk.recvfrom (Bufsize[.flag])
Similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
Sk.send (String[,flag])
Sends data from a string to a connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.
Sk.sendall (String[,flag])
Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
Sk.sendto (string[,flag],address)
Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.
Sk.settimeout (Timeout)
Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as client connections waiting up to 5s)
Sk.getpeername ()
Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
Sk.getsockname ()
Returns the socket's own address. Typically a tuple (ipaddr,port)
Sk.fileno ()
File descriptor for sockets
Socketserver Module
First, the use of the source code analysis
For the default socket server to handle client requests, the request is processed in a blocking manner, and Socketserver enables a colleague to process multiple requests.
#!/usr/bin/env python#coding:utf-8import socketserverimport osclass MyServer (socketserver.baserequesthandler): def Handle (self): Base_path = ' g:/temp ' conn = self.request print ' Connected ... ' while True: Pre_data = Conn.recv (1024x768) #获取请求方法, filename, file size cmd,file_name,file_size = Pre_data.split (' | ') # Prevent sticky packets and send a signal to the client. Conn.sendall (' nothing ') #已经接收文件的大小 recv_size = 0 #上传文件路径拼接 File_di R = Os.path.join (base_path,file_name) f = file (File_dir, ' WB ') flag = True while flag: #未上传完毕, if int (file_size) >recv_size: #最多接收1024, may receive less than 1024 data = CONN.RECV (1024x768) recv_size+=len (data) #写入文件 F.write (d ATA) #上传完毕, exit the loop else:recv_size = 0 Flag = FAlse print ' upload successed. ' F.close () instance = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 9999), MyServer) Instance.serve_forever ()
#!/usr/bin/env python#coding:utf-8import socketimport sysimport osip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket () Sk.connect (ip_port) container = {' key ': ', ' data ': '}while True: # Client input path to upload file input = raw_input (' Path: ') # Gets the file name according to the path file_name = os.path.basename (path) # Gets the size file_size=os.stat (path). St_size # Send file name and file size sk.send (file_name+ ' | ') +str (File_size) # To prevent sticky packets, after sending the file name and size to the past, wait for the server to receive it until a signal is received from the server (stating that the server has received it) Sk.recv (1024x768) send_size = 0 f= file (path, ' RB ') flag = True while flag: if send_size + 1024x768 >file_size: data = F.read ( file_size-send_size) Flag = False else: data = F.read (1024x768) send_size+=1024 sk.send (data) f.close () sk.close ()
For large file processing:
Send writes only once to the buffer, and the incoming content does not necessarily end, so the return value is the actual size of the send. For example: 1023M = Send (1g data) so the actual is sent 1023M, the other 1M is leaked Sendall, the internal call send will continue to write to the buffer until the file is all finished. Example: sendall (1g data) first time: send (1023M) second time: Send (1M) ========== when sending large files, it is not possible to read all 1G memory, when the open file is required, Read it at 1.1 and then send it again. # Large File size File_size=os.stat (file path). st_size # Open Large file F = file (filename path, ' RB ') # data already sent Send_size = 0 while Flag: # Large files are only left 1024 bytes, others have already been sent. if send_size + 1024x768 > File_size: # reads less than 1024 bytes from a large file, possibly 10 bytes ... data = F.read (file_size-send_size) Flag = False Else: # reads 1024 bytes of data = F.read (1024x768) from a large file # Record how many bytes have been sent send_size + = 1024x768 # Send data from large files to buffer in batches, up to 1024 bytes per sk.sendall (data)
python--Eighth Day Summary