Python--typeerror: ' str ' does not support the buffer interface

Source: Internet
Author: User

ImportSocketImportSysport=51423Host="localhost"Data=b"x"*10485760#在字符串前加 B is the string into the bytes class. sock=Socket.socket (Socket.af_inet,socket. Sock_stream) Sock.connect ((host,port)) Byteswritten=0 whilebyteswritten<len (data): Startpos=Byteswritten Endpos= Min (byteswritten+1024, Len (data)) Byteswritten+=sock.send (Data[startpos:endpos]) sys.stdout.write ("wrote%d bytes\r"%Byteswritten) Sys.stdout.flush () Sock.shutdown (1)Print("All data sent.") whileTrue:buf= SOCK.RECV (1024). The decode () #.decode () function converts the bytes type to the str type. if  notLen (buf): Breaksys.stdout.write (BUF)

Problem solving:

in Python 3, Bytes strings and Unicode strings is now, different types. Since sockets is not aware of string encodings, they is using raw bytes strings, that has a slightly different interfac E from Unicode strings.

In Python 3, the bytes type and the Unicode string type are now two different types. The socket module now does not recognize Unicode STR types, and they now use the bytes byte class.

So, now, whenever you has a Unicode string that is need to the use as a byte string, which you need to encode () it.

If you had a byte string, you need to decode it-to-use it as a regular (Python 2.x) string.

So now whenever you have a Unicode str class but you need a bytes class, you need to convert it using the Encode () function.

When you have a bytes type, you need to convert it with the Decode () function as a normal Unicode string.

Unicode strings is quotes enclosed strings. Bytes strings is B "" enclosed strings

The Unicode STR class is directly enclosed in quotation marks "* * *", and the bytes string needs to be added B before the quotation mark "". B "Test String"

When you use Client_socket.send (data), replace it by Client_socket.send (Data.encode ()).

When you use Socket.send (data), use Socket.send (Data.encode ()) instead.

When you get the data using data = CLIENT_SOCKET.RECV, replace it by Data =client_socket.recv. Decode ()

When you use DATA=SOCKET.RECV (512), use SOCKET.RECV. Decode () instead.

============================================ Knowledge Extension ========================================

First, the bytes/str of Python 3

Original: The Bytes/str dichotomy in Python 3

Understanding the Bytes/str, understanding the Codecs module is easy.

The most important new feature of Python 3 is probably a clearer distinction between text and binary data. Text is always Unicode, represented by the STR type, and binary data is represented by the bytes type. Python 3 does not mix str and bytes in any implicit way, which makes the distinction between them particularly clear. You cannot stitch strings and byte packets, search for strings in a byte packet (or vice versa), or pass a string into a function with a byte packet (or vice versa). It's a good thing .

In any case, the line between the string and the byte packet is inevitable, and the following diagram is important to keep in mind:

A string can be encoded into a byte packet, and a byte packet can be decoded into a string.

>>> ‘€20‘.encode(‘utf-8‘)b‘\xe2\x82\xac20‘>>> b‘\xe2\x82\xac20‘.decode(‘utf-8‘)‘€20‘

This is the problem: strings are an abstract representation of text. Strings are composed of characters, and the characters are abstract entities that are not related to any particular binary representation. We live in the ignorance of happiness while manipulating strings. We can split and shard strings, and we can stitch and search strings. We don't care how they are represented internally, and each character in the string is saved in a few bytes. It is only when the strings are encoded into a byte package (for example, to send them on a channel) or decoded from a byte packet (reverse operation) that we begin to pay attention to this.

The parameters passed in encode and decode are encoded (or codec). Encoding is a way of representing abstract characters in binary data. There are many kinds of coding at present. The UTF-8 given above is one of them, and here is another:

>>> ‘€20‘.encode(‘iso-8859-15‘)b‘\xa420‘>>> b‘\xa420‘.decode(‘iso-8859-15‘)‘€20‘

Coding is a critical part of this transformation process. Away from the code, Bytes object B ' \xa420 ' is just a bunch of bits. The encoding gives it meaning. With different encodings, the meaning of this heap of bits can be very different:

>>> b‘\xa420‘.decode(‘windows-1255‘)‘?20‘


Ii. Introduction of Codecs module

Codecs is the abbreviation for encoders and decoders.

The

Codecs module provides a lookup method for the processing of character encodings that we solve, which accepts parameters for a character encoding name and returns the codecs corresponding to the specified character encoding. A Codecinfo object that contains references to function objects and class objects for encoder, decoder, StreamReader, and StreamWriter. To simplify the invocation of the lookup method, codecs also provides getencoder (encoding), Getdecoder (encoding), Getreader (encoding), and getwriter (encoding) methods Further, simplifying access to StreamReader, StreamWriter, and Streamreaderwriter for specific character encodings, codecs provides the open method more directly, passing character-encoded names through the encoding parameter to get Two-way service for encoder and decoder.


The power of this module is that it provides a way to handle string encoding in a stream, which is useful when there is a lot of data to be processed.
You can use Incrementalencoder and Incrementaldecoder, but it's highly recommended to use StreamReader and StreamWriter, because using them will greatly simplify your code.

For example, there is a Test.txt file, which is encoded as GBK, and now I need to convert its encoding to UTF8, you can write the following code:

[Python]View Plaincopy
    1. #coding: UTF8 2
    2. Import Codecs
    3. # Open File If you open the file with the Codecs.open () method here, you do not have to create reader and writer
    4. Fin = open (' test.txt ', ' R ')
    5. Fout = open (' utf8.txt ', ' W ')
    6. # Get StreamReader
    7. Reader = Codecs.getreader (' GBK ') (Fin)
    8. # Get StreamWriter
    9. writer = codecs.getwriter (' UTF8 ') (fout)
    10. DIN = Reader.read (ten)
    11. While DIN:
    12. Writer.write (DIN)
    13. DIN = Reader.read (10)

Python--typeerror: ' str ' does not support the buffer interface

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.