Hướng dẫn codecs python
Source code: Lib/codecs.py Show
This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are
text encodings, which encode text to bytes (and decode bytes to text), but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to be used specifically with text encodings
or with codecs that encode to The module defines the following functions for encoding and decoding with any codec: codecs. encode (obj, encoding='utf-8',
errors='strict')¶Encodes obj using the codec registered for encoding. Errors may be given to set the desired error handling scheme. The default error handler is codecs. decode (obj, encoding='utf-8', errors='strict')¶Decodes obj using the codec registered for encoding. Errors may be given to set the desired error
handling scheme. The default error handler is The full details for each codec can also be looked up directly: codecs. lookup (encoding)¶Looks
up the codec info in the Python codec registry and returns a Encodings are first looked up in the registry’s cache. If not found, the list of registered search functions is scanned. If no codecs. CodecInfo (encode, decode,
streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)¶Codec details when looking up the codec registry. The constructor arguments are stored in attributes of the same name: name ¶The name of the encoding. encode ¶ decode ¶The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the
incrementalencoder ¶ incrementaldecoder ¶Incremental encoder and decoder classes or factory functions.
These have to provide the interface defined by the base classes streamwriter ¶ streamreader ¶Stream writer and reader classes or factory functions. These have to provide the interface defined by the base classes To simplify access to the various codec components, the module provides these additional functions which use
codecs. getencoder (encoding)¶Look up the codec for the given encoding and return its encoder function. Raises a
codecs. getdecoder (encoding)¶Look up the codec for the given encoding and return its decoder function. Raises a codecs. getincrementalencoder (encoding)¶Look up the codec for the given encoding and return its incremental encoder class or factory function. Raises a codecs. getincrementaldecoder (encoding)¶Look up the codec for the given encoding and return its incremental decoder class or factory function. Raises a
codecs. getreader (encoding)¶
Look up the codec for the given encoding and return its Raises a codecs. getwriter (encoding)¶Look up the codec for the given encoding and return its Raises a
Custom codecs are made available by registering a suitable codec search function: codecs. register (search_function)¶Register a codec search function. Search functions are expected to take one argument, being the encoding name in all lower case letters with hyphens and spaces converted to underscores, and return a
Changed in version 3.9: Hyphens and spaces are converted to underscore. codecs. unregister (search_function)¶Unregister a codec search function and clear the registry’s cache. If the search function is not registered, do nothing. New in version 3.10. While the builtin
codecs. open (filename, mode='r', encoding=None, errors='strict', buffering=- 1)¶Open an encoded file
using the given mode and return an instance of Note Underlying encoded files are always opened in binary mode. No automatic conversion of encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used. errors may be given to define the error handling. It defaults
to buffering has the same meaning as for the built-in codecs. EncodedFile (file, data_encoding, file_encoding=None, errors='strict')¶Return a Data written to the wrapped file is decoded according to the given data_encoding and then written to the original file as bytes using file_encoding. Bytes read from the original file are decoded according to file_encoding, and the result is encoded using data_encoding. If file_encoding is not given, it defaults to data_encoding. errors may be given to define the error handling. It defaults to codecs. iterencode (iterator,
encoding, errors='strict', **kwargs)¶Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator. The errors argument (as well as any other keyword argument) is passed through to the incremental encoder. This function requires that the codec accept text codecs. iterdecode (iterator, encoding, errors='strict', **kwargs)¶Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator. The errors argument (as well as any other keyword argument) is passed through to the incremental decoder. This function requires that the codec accept The module also provides the following constants which are useful for reading and writing to platform dependent files: codecs. BOM ¶ codecs. BOM_BE ¶ codecs. BOM_LE ¶ codecs. BOM_UTF8 ¶ codecs. BOM_UTF16 ¶ codecs. BOM_UTF16_BE ¶
codecs. BOM_UTF16_LE ¶ codecs. BOM_UTF32 ¶
codecs. BOM_UTF32_BE ¶ codecs. BOM_UTF32_LE ¶These constants define various byte sequences, being Unicode byte order marks (BOMs) for several encodings. They are used
in UTF-16 and UTF-32 data streams to indicate the byte order used, and in UTF-8 as a Unicode signature. Codec Base Classes¶The
Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors. Error Handlers¶To simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument: >>> 'German ß, ♬'.encode(encoding='ascii', errors='backslashreplace') b'German \\xdf, \\u266c' >>> 'German ß, ♬'.encode(encoding='ascii', errors='xmlcharrefreplace') b'German ß, ♬' The following error handlers can be used with all Python Standard Encodings codecs:
The following error handlers are only applicable to encoding (within text encodings):
In addition, the following error handler is specific to the given codecs:
New in version 3.1: The Changed in version 3.4: The New in version 3.5: The Changed in version 3.5: The The set of allowed values can be extended by registering a new named error handler: codecs. register_error (name, error_handler)¶Register the error handling function error_handler under the name name. The error_handler argument will be called during encoding and decoding in case of an error, when name is specified as the errors parameter. For encoding, error_handler will be called with a Decoding and translating works similarly, except Previously registered error handlers (including the standard error handlers) can be looked up by name: codecs. lookup_error (name)¶Return the error handler previously registered under the name name. Raises a The following standard error handlers are also made available as module level functions: codecs. strict_errors (exception)¶Implements the Each encoding or decoding error raises a
codecs. ignore_errors (exception)¶Implements the Malformed data is ignored; encoding or decoding is continued without further notice. codecs. replace_errors (exception)¶Implements the Substitutes codecs. backslashreplace_errors (exception)¶Implements the Malformed data is replaced by a backslashed escape sequence. On encoding, use the hexadecimal form of Unicode code point with formats Changed in version 3.5: Works with decoding and translating. codecs. xmlcharrefreplace_errors (exception)¶Implements the The unencodable character is replaced by an appropriate XML/HTML numeric character reference, which is a decimal form of Unicode code point with format codecs. namereplace_errors (exception)¶Implements the The unencodable character is replaced by a
New in version 3.5. Stateless Encoding and Decoding¶The base Codec. encode (input,
errors='strict')¶Encodes the object input and returns a tuple (output object, length consumed). For instance, text encoding converts a string object to a bytes object using a
particular character set encoding (e.g., The errors argument defines the error handling to apply. It defaults to The method may not store state in the The encoder must be able to handle zero length input and return an empty object of the output object type in this situation. Codec. decode (input, errors='strict')¶Decodes the object input and returns a tuple (output object, length consumed). For instance, for a text encoding, decoding converts a bytes object encoded using a particular character set encoding to a string object. For text encodings and bytes-to-bytes codecs, input must be a bytes object or one which provides the read-only buffer interface – for example, buffer objects and memory mapped files. The errors argument defines the error handling to
apply. It defaults to The method may not store state in the The decoder must be able to handle zero length input and return an empty object of the output object type in this situation. Incremental Encoding and Decoding¶The The
joined output of calls to the IncrementalEncoder Objects¶The codecs. IncrementalEncoder (errors='strict')¶Constructor for an
All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry. The
The errors argument will be assigned to an attribute of the
same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the encode (object,
final=False)¶Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to
reset ()¶Reset the encoder to the initial state. The
output is discarded: call getstate ()¶Return the current state of the encoder which must be an integer. The implementation should make sure that
setstate (state)¶Set the state of the encoder to state. state must be an encoder state returned by
IncrementalDecoder Objects¶The
codecs. IncrementalDecoder (errors='strict')¶Constructor for an All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry. The The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the decode (object, final=False)¶Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to
reset ()¶Reset the decoder to the initial state. getstate ()¶Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that setstate (state)¶Set the state of the decoder to state. state must be a decoder state returned by
Stream Encoding and Decoding¶The
StreamWriter Objects¶The codecs. StreamWriter (stream, errors='strict')¶Constructor for a All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry. The stream argument must be a file-like object open for writing text or binary data, as appropriate for the specific codec. The The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the
write (object)¶Writes the object’s contents encoded to the stream. writelines (list)¶Writes the concatenated iterable of strings to the stream (possibly by reusing the reset ()¶Resets the codec buffers used for keeping internal state. Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state. In addition to the above methods, the StreamReader Objects¶The codecs. StreamReader (stream, errors='strict')¶Constructor for a All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry. The stream argument must be a file-like object open for reading text or binary data, as appropriate for the specific codec. The The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the
The set of allowed values for the errors argument can be extended with read (size=- 1,
chars=- 1, firstline=False)¶Decodes data from the stream and returns the resulting object. The chars argument indicates the number of decoded code points or bytes to return. The
The size argument indicates the approximate maximum number of encoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. This parameter is intended to prevent having to decode huge files in one step. The firstline flag indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines. The method should use a greedy read strategy meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too. readline (size=None, keepends=True)¶Read one line from the input stream and return the decoded data. size, if given, is passed as size argument
to the stream’s If keepends is false line-endings will be stripped from the lines returned. readlines (sizehint=None,
keepends=True)¶Read all lines available on the input stream and return them as a list of lines. Line-endings are implemented using the codec’s sizehint, if given, is passed as the size argument to the stream’s reset ()¶Resets the codec buffers used for keeping internal state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors. In addition to the above methods, the
StreamReaderWriter Objects¶The
The design is such that one can use the factory functions returned by the codecs. StreamReaderWriter (stream, Reader, Writer, errors='strict')¶Creates a
StreamRecoder Objects¶The The design is such that one can use the factory functions returned by the
codecs. StreamRecoder (stream, encode, decode, Reader, Writer,
errors='strict')¶Creates a You can use these objects to do transparent transcodings, e.g., from Latin-1 to UTF-8 and back. The stream argument must be a file-like object. The encode and decode arguments must adhere to the Error handling is done in the same way as defined for the stream readers and writers.
Encodings and Unicode¶Strings are stored internally as sequences of code points in range The simplest text encoding (called There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes All of these encodings can only encode 256 of the 1114112 code points defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each code point as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These
two encodings are called There’s
another encoding that is able to encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four
The least significant bit of the Unicode character is the rightmost x bit. As UTF-8 is an 8-bit encoding no BOM is required and any Without external information it’s impossible to reliably determine which encoding was used for encoding a string. Each charmap encoding can decode any random byte sequence. However that’s not possible with UTF-8, as UTF-8
byte sequences have a structure that doesn’t allow arbitrary byte sequences. To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python calls
in iso-8859-1), this increases the probability that a Standard Encodings¶Python comes with
a number of codecs built-in, either implemented as C functions or with dictionaries as mapping tables. The following table lists the codecs by name, together with a few common aliases, and the languages for which the encoding is likely used. Neither the list of aliases nor the list of languages is meant to be exhaustive. Notice that spelling alternatives that only differ in case or use a hyphen instead of an underscore are also valid aliases; therefore, e.g. CPython implementation detail: Some common encodings can bypass the codecs lookup machinery to improve performance. These optimization opportunities are only recognized by CPython for a limited set of (case insensitive) aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and the same using underscores instead of dashes. Using alternative aliases for these encodings may result in slower execution. Changed in version 3.6: Optimization opportunity recognized for us-ascii. Many of the character sets support the same languages. They vary in individual characters (e.g. whether the EURO SIGN is supported or not), and in the assignment of characters to code positions. For the European languages in particular, the following variants typically exist:
Changed in version 3.4: The utf-16* and utf-32* encoders no longer allow surrogate code points ( Changed in version 3.8: Python Specific Encodings¶A number of predefined codecs are specific to Python, so their codec names have no meaning outside Python. These are listed in the tables below based on the expected input and output types (note that while text encodings are the most common use case for codecs, the underlying codec infrastructure supports arbitrary data transforms rather than just text encodings). For asymmetric codecs, the stated meaning describes the encoding direction. Text Encodings¶The following codecs provide
Changed in version 3.8: “unicode_internal” codec is removed. Binary Transforms¶The following codecs provide binary transforms: bytes-like
object to
In addition to bytes-like objects, New in version 3.2: Restoration of the binary transforms. Changed in version 3.4: Restoration of the aliases for the binary transforms. Text Transforms¶The following codec provides a text transform: a
New in version 3.2: Restoration of the Changed in version 3.4: Restoration of the encodings.idna — Internationalized Domain Names in Applications¶This module implements
RFC 3490 (Internationalized Domain Names in Applications) and RFC 3492 (Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)). It builds upon the If you need the IDNA 2008 standard from RFC 5891 and RFC 5895, use the third-party idna module. These RFCs together define a protocol to support non-ASCII characters in domain names. A domain name containing non-ASCII characters (such as Python supports this conversion in several ways: the When receiving host names from the wire (such as in reverse name lookup), no automatic conversion to Unicode is performed: applications wishing to present such host names to the user should decode them to Unicode. The module
encodings.idna. nameprep (label)¶Return the nameprepped version of label. The implementation currently assumes query strings, so encodings.idna. ToASCII (label)¶Convert a label to ASCII, as specified in RFC 3490. encodings.idna. ToUnicode (label)¶Convert a label to Unicode, as specified in RFC 3490. encodings.mbcs — Windows ANSI codepage¶This module implements the ANSI codepage (CP_ACP). Availability: Windows only. Changed in version 3.3: Support any error handler. Changed in version 3.2: Before 3.2, the errors argument was ignored; encodings.utf_8_sig — UTF-8 codec with BOM signature¶This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this is only done once (on the first write to the byte stream). On decoding, an optional UTF-8 encoded BOM at the start of the data will be skipped. |