同步操作将从 OpenHarmony-SIG/python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
""" codecs -- Python Codec Registry, API and helpers.Written by Marc-Andre Lemburg (mal@lemburg.com).(c) Copyright CNRI, All Rights Reserved. NO WARRANTY."""import builtinsimport sys### Registry and builtin stateless codec functionstry:from _codecs import *except ImportError as why:raise SystemError('Failed to load the builtin codecs: %s' % why)__all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE","BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE","BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE","BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE","CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder","StreamReader", "StreamWriter","StreamReaderWriter", "StreamRecoder","getencoder", "getdecoder", "getincrementalencoder","getincrementaldecoder", "getreader", "getwriter","encode", "decode", "iterencode", "iterdecode","strict_errors", "ignore_errors", "replace_errors","xmlcharrefreplace_errors","backslashreplace_errors", "namereplace_errors","register_error", "lookup_error"]### Constants## Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)# and its possible byte string values# for UTF8/UTF16/UTF32 output and little/big endian machines## UTF-8BOM_UTF8 = b'\xef\xbb\xbf'# UTF-16, little endianBOM_LE = BOM_UTF16_LE = b'\xff\xfe'# UTF-16, big endianBOM_BE = BOM_UTF16_BE = b'\xfe\xff'# UTF-32, little endianBOM_UTF32_LE = b'\xff\xfe\x00\x00'# UTF-32, big endianBOM_UTF32_BE = b'\x00\x00\xfe\xff'if sys.byteorder == 'little':# UTF-16, native endiannessBOM = BOM_UTF16 = BOM_UTF16_LE# UTF-32, native endiannessBOM_UTF32 = BOM_UTF32_LEelse:# UTF-16, native endiannessBOM = BOM_UTF16 = BOM_UTF16_BE# UTF-32, native endiannessBOM_UTF32 = BOM_UTF32_BE# Old broken names (don't use in new code)BOM32_LE = BOM_UTF16_LEBOM32_BE = BOM_UTF16_BEBOM64_LE = BOM_UTF32_LEBOM64_BE = BOM_UTF32_BE### Codec base classes (defining the API)class CodecInfo(tuple):"""Codec details when looking up the codec registry"""# Private API to allow Python 3.4 to blacklist the known non-Unicode# codecs in the standard library. A more general mechanism to# reliably distinguish test encodings from other codecs will hopefully# be defined for Python 3.5## See http://bugs.python.org/issue19619_is_text_encoding = True # Assume codecs are text encodings by defaultdef __new__(cls, encode, decode, streamreader=None, streamwriter=None,incrementalencoder=None, incrementaldecoder=None, name=None,*, _is_text_encoding=None):self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))self.name = nameself.encode = encodeself.decode = decodeself.incrementalencoder = incrementalencoderself.incrementaldecoder = incrementaldecoderself.streamwriter = streamwriterself.streamreader = streamreaderif _is_text_encoding is not None:self._is_text_encoding = _is_text_encodingreturn selfdef __repr__(self):return "<%s.%s object for encoding %s at %#x>" % \(self.__class__.__module__, self.__class__.__qualname__,self.name, id(self))class Codec:""" Defines the interface for stateless encoders/decoders.The .encode()/.decode() methods may use different errorhandling schemes by providing the errors argument. Thesestring values are predefined:'strict' - raise a ValueError error (or a subclass)'ignore' - ignore the character and continue with the next'replace' - replace with a suitable replacement character;Python will use the official U+FFFD REPLACEMENTCHARACTER for the builtin Unicode codecs ondecoding and '?' on encoding.'surrogateescape' - replace with private code points U+DCnn.'xmlcharrefreplace' - Replace with the appropriate XMLcharacter reference (only for encoding).'backslashreplace' - Replace with backslashed escape sequences.'namereplace' - Replace with \\N{...} escape sequences(only for encoding).The set of allowed values can be extended via register_error."""def encode(self, input, errors='strict'):""" Encodes the object input and returns a tuple (outputobject, length consumed).errors defines the error handling to apply. It defaults to'strict' handling.The method may not store state in the Codec instance. UseStreamWriter for codecs which have to keep state in order tomake encoding efficient.The encoder must be able to handle zero length input andreturn an empty object of the output object type in thissituation."""raise NotImplementedErrordef decode(self, input, errors='strict'):""" Decodes the object input and returns a tuple (outputobject, length consumed).input must be an object which provides the bf_getreadbufbuffer slot. Python strings, buffer objects and memorymapped files are examples of objects providing this slot.errors defines the error handling to apply. It defaults to'strict' handling.The method may not store state in the Codec instance. UseStreamReader for codecs which have to keep state in order tomake decoding efficient.The decoder must be able to handle zero length input andreturn an empty object of the output object type in thissituation."""raise NotImplementedErrorclass IncrementalEncoder(object):"""An IncrementalEncoder encodes an input in multiple steps. The input canbe passed piece by piece to the encode() method. The IncrementalEncoderremembers the state of the encoding process between calls to encode()."""def __init__(self, errors='strict'):"""Creates an IncrementalEncoder instance.The IncrementalEncoder may use different error handling schemes byproviding the errors keyword argument. See the module docstringfor a list of possible values."""self.errors = errorsself.buffer = ""def encode(self, input, final=False):"""Encodes input and returns the resulting object."""raise NotImplementedErrordef reset(self):"""Resets the encoder to the initial state."""def getstate(self):"""Return the current state of the encoder."""return 0def setstate(self, state):"""Set the current state of the encoder. state must have beenreturned by getstate()."""class BufferedIncrementalEncoder(IncrementalEncoder):"""This subclass of IncrementalEncoder can be used as the baseclass for anincremental encoder if the encoder must keep some of the output in abuffer between calls to encode()."""def __init__(self, errors='strict'):IncrementalEncoder.__init__(self, errors)# unencoded input that is kept between calls to encode()self.buffer = ""def _buffer_encode(self, input, errors, final):# Overwrite this method in subclasses: It must encode input# and return an (output, length consumed) tupleraise NotImplementedErrordef encode(self, input, final=False):# encode input (taking the buffer into account)data = self.buffer + input(result, consumed) = self._buffer_encode(data, self.errors, final)# keep unencoded input until the next callself.buffer = data[consumed:]return resultdef reset(self):IncrementalEncoder.reset(self)self.buffer = ""def getstate(self):return self.buffer or 0def setstate(self, state):self.buffer = state or ""class IncrementalDecoder(object):"""An IncrementalDecoder decodes an input in multiple steps. The input canbe passed piece by piece to the decode() method. The IncrementalDecoderremembers the state of the decoding process between calls to decode()."""def __init__(self, errors='strict'):"""Create an IncrementalDecoder instance.The IncrementalDecoder may use different error handling schemes byproviding the errors keyword argument. See the module docstringfor a list of possible values."""self.errors = errorsdef decode(self, input, final=False):"""Decode input and returns the resulting object."""raise NotImplementedErrordef reset(self):"""Reset the decoder to the initial state."""def getstate(self):"""Return the current state of the decoder.This must be a (buffered_input, additional_state_info) tuple.buffered_input must be a bytes object containing bytes thatwere passed to decode() that have not yet been converted.additional_state_info must be a non-negative integerrepresenting the state of the decoder WITHOUT yet havingprocessed the contents of buffered_input. In the initial stateand after reset(), getstate() must return (b"", 0)."""return (b"", 0)def setstate(self, state):"""Set the current state of the decoder.state must have been returned by getstate(). The effect ofsetstate((b"", 0)) must be equivalent to reset()."""class BufferedIncrementalDecoder(IncrementalDecoder):"""This subclass of IncrementalDecoder can be used as the baseclass for anincremental decoder if the decoder must be able to handle incompletebyte sequences."""def __init__(self, errors='strict'):IncrementalDecoder.__init__(self, errors)# undecoded input that is kept between calls to decode()self.buffer = b""def _buffer_decode(self, input, errors, final):# Overwrite this method in subclasses: It must decode input# and return an (output, length consumed) tupleraise NotImplementedErrordef decode(self, input, final=False):# decode input (taking the buffer into account)data = self.buffer + input(result, consumed) = self._buffer_decode(data, self.errors, final)# keep undecoded input until the next callself.buffer = data[consumed:]return resultdef reset(self):IncrementalDecoder.reset(self)self.buffer = b""def getstate(self):# additional state info is always 0return (self.buffer, 0)def setstate(self, state):# ignore additional state infoself.buffer = state[0]## The StreamWriter and StreamReader class provide generic working# interfaces which can be used to implement new encoding submodules# very easily. See encodings/utf_8.py for an example on how this is# done.#class StreamWriter(Codec):def __init__(self, stream, errors='strict'):""" Creates a StreamWriter instance.stream must be a file-like object open for writing.The StreamWriter may use different error handlingschemes by providing the errors keyword argument. Theseparameters are predefined:'strict' - raise a ValueError (or a subclass)'ignore' - ignore the character and continue with the next'replace'- replace with a suitable replacement character'xmlcharrefreplace' - Replace with the appropriate XMLcharacter reference.'backslashreplace' - Replace with backslashed escapesequences.'namereplace' - Replace with \\N{...} escape sequences.The set of allowed parameter values can be extended viaregister_error."""self.stream = streamself.errors = errorsdef write(self, object):""" Writes the object's contents encoded to self.stream."""data, consumed = self.encode(object, self.errors)self.stream.write(data)def writelines(self, list):""" Writes the concatenated list of strings to the streamusing .write()."""self.write(''.join(list))def reset(self):""" Flushes and resets the codec buffers used for keeping state.Calling this method should ensure that the data on theoutput is put into a clean state, that allows appendingof new fresh data without having to rescan the wholestream to recover state."""passdef seek(self, offset, whence=0):self.stream.seek(offset, whence)if whence == 0 and offset == 0:self.reset()def __getattr__(self, name,getattr=getattr):""" Inherit all other methods from the underlying stream."""return getattr(self.stream, name)def __enter__(self):return selfdef __exit__(self, type, value, tb):self.stream.close()###class StreamReader(Codec):charbuffertype = strdef __init__(self, stream, errors='strict'):""" Creates a StreamReader instance.stream must be a file-like object open for reading.The StreamReader may use different error handlingschemes by providing the errors keyword argument. Theseparameters are predefined:'strict' - raise a ValueError (or a subclass)'ignore' - ignore the character and continue with the next'replace'- replace with a suitable replacement character'backslashreplace' - Replace with backslashed escape sequences;The set of allowed parameter values can be extended viaregister_error."""self.stream = streamself.errors = errorsself.bytebuffer = b""self._empty_charbuffer = self.charbuffertype()self.charbuffer = self._empty_charbufferself.linebuffer = Nonedef decode(self, input, errors='strict'):raise NotImplementedErrordef read(self, size=-1, chars=-1, firstline=False):""" Decodes data from the stream self.stream and returns theresulting object.chars indicates the number of decoded code points or bytes toreturn. read() will never return more data than requested,but it might return less, if there is not enough available.size indicates the approximate maximum number of decodedbytes or code points to read for decoding. The decodercan modify this setting as appropriate. The default value-1 indicates to read and decode as much as possible. sizeis intended to prevent having to decode huge files in onestep.If firstline is true, and a UnicodeDecodeError happensafter the first line terminator in the input only the first linewill be returned, the rest of the input will be kept until thenext call to read().The method should use a greedy read strategy, meaning thatit should read as much data as is allowed within thedefinition of the encoding and the given size, e.g. ifoptional encoding endings or state markers are availableon the stream, these should be read too."""# If we have lines cached, first merge them back into charactersif self.linebuffer:self.charbuffer = self._empty_charbuffer.join(self.linebuffer)self.linebuffer = Noneif chars < 0:# For compatibility with other read() methods that take a# single argumentchars = size# read until we get the required number of characters (if available)while True:# can the request be satisfied from the character buffer?if chars >= 0:if len(self.charbuffer) >= chars:break# we need more dataif size < 0:newdata = self.stream.read()else:newdata = self.stream.read(size)# decode bytes (those remaining from the last call included)data = self.bytebuffer + newdataif not data:breaktry:newchars, decodedbytes = self.decode(data, self.errors)except UnicodeDecodeError as exc:if firstline:newchars, decodedbytes = \self.decode(data[:exc.start], self.errors)lines = newchars.splitlines(keepends=True)if len(lines)<=1:raiseelse:raise# keep undecoded bytes until the next callself.bytebuffer = data[decodedbytes:]# put new characters in the character bufferself.charbuffer += newchars# there was no data availableif not newdata:breakif chars < 0:# Return everything we've gotresult = self.charbufferself.charbuffer = self._empty_charbufferelse:# Return the first chars charactersresult = self.charbuffer[:chars]self.charbuffer = self.charbuffer[chars:]return resultdef readline(self, size=None, keepends=True):""" Read one line from the input stream and return thedecoded data.size, if given, is passed as size argument to theread() method."""# If we have lines cached from an earlier read, return# them unconditionallyif self.linebuffer:line = self.linebuffer[0]del self.linebuffer[0]if len(self.linebuffer) == 1:# revert to charbuffer mode; we might need more data# next timeself.charbuffer = self.linebuffer[0]self.linebuffer = Noneif not keepends:line = line.splitlines(keepends=False)[0]return linereadsize = size or 72line = self._empty_charbuffer# If size is given, we call read() only oncewhile True:data = self.read(readsize, firstline=True)if data:# If we're at a "\r" read one extra character (which might# be a "\n") to get a proper line ending. If the stream is# temporarily exhausted we return the wrong line ending.if (isinstance(data, str) and data.endswith("\r")) or \(isinstance(data, bytes) and data.endswith(b"\r")):data += self.read(size=1, chars=1)line += datalines = line.splitlines(keepends=True)if lines:if len(lines) > 1:# More than one line result; the first line is a full line# to returnline = lines[0]del lines[0]if len(lines) > 1:# cache the remaining lineslines[-1] += self.charbufferself.linebuffer = linesself.charbuffer = Noneelse:# only one remaining line, put it back into charbufferself.charbuffer = lines[0] + self.charbufferif not keepends:line = line.splitlines(keepends=False)[0]breakline0withend = lines[0]line0withoutend = lines[0].splitlines(keepends=False)[0]if line0withend != line0withoutend: # We really have a line end# Put the rest back together and keep it until the next callself.charbuffer = self._empty_charbuffer.join(lines[1:]) + \self.charbufferif keepends:line = line0withendelse:line = line0withoutendbreak# we didn't get anything or this was our only tryif not data or size is not None:if line and not keepends:line = line.splitlines(keepends=False)[0]breakif readsize < 8000:readsize *= 2return linedef readlines(self, sizehint=None, keepends=True):""" Read all lines available on the input streamand return them as a list.Line breaks are implemented using the codec's decodermethod and are included in the list entries.sizehint, if given, is ignored since there is no efficientway to finding the true end-of-line."""data = self.read()return data.splitlines(keepends)def reset(self):""" Resets the codec buffers used for keeping state.Note that no stream repositioning should take place.This method is primarily intended to be able to recoverfrom decoding errors."""self.bytebuffer = b""self.charbuffer = self._empty_charbufferself.linebuffer = Nonedef seek(self, offset, whence=0):""" Set the input stream's current position.Resets the codec buffers used for keeping state."""self.stream.seek(offset, whence)self.reset()def __next__(self):""" Return the next decoded line from the input stream."""line = self.readline()if line:return lineraise StopIterationdef __iter__(self):return selfdef __getattr__(self, name,getattr=getattr):""" Inherit all other methods from the underlying stream."""return getattr(self.stream, name)def __enter__(self):return selfdef __exit__(self, type, value, tb):self.stream.close()###class StreamReaderWriter:""" StreamReaderWriter instances allow wrapping streams whichwork in both read and write modes.The design is such that one can use the factory functionsreturned by the codec.lookup() function to construct theinstance."""# Optional attributes set by the file wrappers belowencoding = 'unknown'def __init__(self, stream, Reader, Writer, errors='strict'):""" Creates a StreamReaderWriter instance.stream must be a Stream-like object.Reader, Writer must be factory functions or classesproviding the StreamReader, StreamWriter interface resp.Error handling is done in the same way as defined for theStreamWriter/Readers."""self.stream = streamself.reader = Reader(stream, errors)self.writer = Writer(stream, errors)self.errors = errorsdef read(self, size=-1):return self.reader.read(size)def readline(self, size=None):return self.reader.readline(size)def readlines(self, sizehint=None):return self.reader.readlines(sizehint)def __next__(self):""" Return the next decoded line from the input stream."""return next(self.reader)def __iter__(self):return selfdef write(self, data):return self.writer.write(data)def writelines(self, list):return self.writer.writelines(list)def reset(self):self.reader.reset()self.writer.reset()def seek(self, offset, whence=0):self.stream.seek(offset, whence)self.reader.reset()if whence == 0 and offset == 0:self.writer.reset()def __getattr__(self, name,getattr=getattr):""" Inherit all other methods from the underlying stream."""return getattr(self.stream, name)# these are needed to make "with StreamReaderWriter(...)" work properlydef __enter__(self):return selfdef __exit__(self, type, value, tb):self.stream.close()###class StreamRecoder:""" StreamRecoder instances translate data from one encoding to another.They use the complete set of APIs returned by thecodecs.lookup() function to implement their task.Data written to the StreamRecoder is first decoded into anintermediate format (depending on the "decode" codec) and thenwritten to the underlying stream using an instance of the providedWriter class.In the other direction, data is read from the underlying stream usinga Reader instance and then encoded and returned to the caller."""# Optional attributes set by the file wrappers belowdata_encoding = 'unknown'file_encoding = 'unknown'def __init__(self, stream, encode, decode, Reader, Writer,errors='strict'):""" Creates a StreamRecoder instance which implements a two-wayconversion: encode and decode work on the frontend (thedata visible to .read() and .write()) while Reader and Writerwork on the backend (the data in stream).You can use these objects to do transparenttranscodings from e.g. latin-1 to utf-8 and back.stream must be a file-like object.encode and decode must adhere to the Codec interface; Reader andWriter must be factory functions or classes providing theStreamReader and StreamWriter interfaces resp.Error handling is done in the same way as defined for theStreamWriter/Readers."""self.stream = streamself.encode = encodeself.decode = decodeself.reader = Reader(stream, errors)self.writer = Writer(stream, errors)self.errors = errorsdef read(self, size=-1):data = self.reader.read(size)data, bytesencoded = self.encode(data, self.errors)return datadef readline(self, size=None):if size is None:data = self.reader.readline()else:data = self.reader.readline(size)data, bytesencoded = self.encode(data, self.errors)return datadef readlines(self, sizehint=None):data = self.reader.read()data, bytesencoded = self.encode(data, self.errors)return data.splitlines(keepends=True)def __next__(self):""" Return the next decoded line from the input stream."""data = next(self.reader)data, bytesencoded = self.encode(data, self.errors)return datadef __iter__(self):return selfdef write(self, data):data, bytesdecoded = self.decode(data, self.errors)return self.writer.write(data)def writelines(self, list):data = b''.join(list)data, bytesdecoded = self.decode(data, self.errors)return self.writer.write(data)def reset(self):self.reader.reset()self.writer.reset()def seek(self, offset, whence=0):# Seeks must be propagated to both the readers and writers# as they might need to reset their internal buffers.self.reader.seek(offset, whence)self.writer.seek(offset, whence)def __getattr__(self, name,getattr=getattr):""" Inherit all other methods from the underlying stream."""return getattr(self.stream, name)def __enter__(self):return selfdef __exit__(self, type, value, tb):self.stream.close()### Shortcutsdef open(filename, mode='r', encoding=None, errors='strict', buffering=-1):""" Open an encoded file using the given mode and returna wrapped version providing transparent encoding/decoding.Note: The wrapped version will only accept the object formatdefined by the codecs, i.e. Unicode objects for most builtincodecs. Output is also codec dependent and will usually beUnicode as well.Underlying encoded files are always opened in binary mode.The default file mode is 'r', meaning to open the file in read mode.encoding specifies the encoding which is to be used for thefile.errors may be given to define the error handling. It defaultsto 'strict' which causes ValueErrors to be raised in case anencoding error occurs.buffering has the same meaning as for the builtin open() API.It defaults to -1 which means that the default buffer size willbe used.The returned wrapped file object provides an extra attribute.encoding which allows querying the used encoding. Thisattribute is only available if an encoding was specified asparameter."""if encoding is not None and \'b' not in mode:# Force opening of the file in binary modemode = mode + 'b'file = builtins.open(filename, mode, buffering)if encoding is None:return filetry:info = lookup(encoding)srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)# Add attributes to simplify introspectionsrw.encoding = encodingreturn srwexcept:file.close()raisedef EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):""" Return a wrapped version of file which provides transparentencoding translation.Data written to the wrapped file is decoded accordingto the given data_encoding and then encoded to the underlyingfile using file_encoding. The intermediate data typewill usually be Unicode but depends on the specified codecs.Bytes read from the file are decoded using file_encoding and thenpassed back to the caller 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 defaultsto 'strict' which causes ValueErrors to be raised in case anencoding error occurs.The returned wrapped file object provides two extra attributes.data_encoding and .file_encoding which reflect the givenparameters of the same name. The attributes can be used forintrospection by Python programs."""if file_encoding is None:file_encoding = data_encodingdata_info = lookup(data_encoding)file_info = lookup(file_encoding)sr = StreamRecoder(file, data_info.encode, data_info.decode,file_info.streamreader, file_info.streamwriter, errors)# Add attributes to simplify introspectionsr.data_encoding = data_encodingsr.file_encoding = file_encodingreturn sr### Helpers for codec lookupdef getencoder(encoding):""" Lookup up the codec for the given encoding and returnits encoder function.Raises a LookupError in case the encoding cannot be found."""return lookup(encoding).encodedef getdecoder(encoding):""" Lookup up the codec for the given encoding and returnits decoder function.Raises a LookupError in case the encoding cannot be found."""return lookup(encoding).decodedef getincrementalencoder(encoding):""" Lookup up the codec for the given encoding and returnits IncrementalEncoder class or factory function.Raises a LookupError in case the encoding cannot be foundor the codecs doesn't provide an incremental encoder."""encoder = lookup(encoding).incrementalencoderif encoder is None:raise LookupError(encoding)return encoderdef getincrementaldecoder(encoding):""" Lookup up the codec for the given encoding and returnits IncrementalDecoder class or factory function.Raises a LookupError in case the encoding cannot be foundor the codecs doesn't provide an incremental decoder."""decoder = lookup(encoding).incrementaldecoderif decoder is None:raise LookupError(encoding)return decoderdef getreader(encoding):""" Lookup up the codec for the given encoding and returnits StreamReader class or factory function.Raises a LookupError in case the encoding cannot be found."""return lookup(encoding).streamreaderdef getwriter(encoding):""" Lookup up the codec for the given encoding and returnits StreamWriter class or factory function.Raises a LookupError in case the encoding cannot be found."""return lookup(encoding).streamwriterdef iterencode(iterator, encoding, errors='strict', **kwargs):"""Encoding iterator.Encodes the input strings from the iterator using an IncrementalEncoder.errors and kwargs are passed through to the IncrementalEncoderconstructor."""encoder = getincrementalencoder(encoding)(errors, **kwargs)for input in iterator:output = encoder.encode(input)if output:yield outputoutput = encoder.encode("", True)if output:yield outputdef iterdecode(iterator, encoding, errors='strict', **kwargs):"""Decoding iterator.Decodes the input strings from the iterator using an IncrementalDecoder.errors and kwargs are passed through to the IncrementalDecoderconstructor."""decoder = getincrementaldecoder(encoding)(errors, **kwargs)for input in iterator:output = decoder.decode(input)if output:yield outputoutput = decoder.decode(b"", True)if output:yield output### Helpers for charmap-based codecsdef make_identity_dict(rng):""" make_identity_dict(rng) -> dictReturn a dictionary where elements of the rng sequence aremapped to themselves."""return {i:i for i in rng}def make_encoding_map(decoding_map):""" Creates an encoding map from a decoding map.If a target mapping in the decoding map occurs multipletimes, then that target is mapped to None (undefined mapping),causing an exception when encountered by the charmap codecduring translation.One example where this happens is cp875.py which decodesmultiple character to \\u001a."""m = {}for k,v in decoding_map.items():if not v in m:m[v] = kelse:m[v] = Nonereturn m### error handlerstry:strict_errors = lookup_error("strict")ignore_errors = lookup_error("ignore")replace_errors = lookup_error("replace")xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")backslashreplace_errors = lookup_error("backslashreplace")namereplace_errors = lookup_error("namereplace")except LookupError:# In --disable-unicode builds, these error handler are missingstrict_errors = Noneignore_errors = Nonereplace_errors = Nonexmlcharrefreplace_errors = Nonebackslashreplace_errors = Nonenamereplace_errors = None# Tell modulefinder that using codecs probably needs the encodings# package_false = 0if _false:import encodings### Testsif __name__ == '__main__':# Make stdout translate Latin-1 output into UTF-8 outputsys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')# Have stdin translate Latin-1 input into UTF-8 inputsys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。