cinap_lenrekadd hg and python4bb9e2215 years agoHistory
1034 lines · 32.5 KB · Python
RawDownload
                    if not keepends:                        line = line.splitlines(False)[0]                    break                line0withend = lines[0]                line0withoutend = lines[0].splitlines(False)[0]                if line0withend != line0withoutend: # We really have a line end                    # Put the rest back together and keep it until the next call                    self.charbuffer = "".join(lines[1:]) + self.charbuffer                    if keepends:                        line = line0withend                    else:                        line = line0withoutend                    break            # we didn't get anything or this was our only try            if not data or size is not None:                if line and not keepends:                    line = line.splitlines(False)[0]                break            if readsize<8000:                readsize *= 2        return line     def readlines(self, sizehint=None, keepends=True):         """ Read all lines available on the input stream            and return them as list of lines.             Line breaks are implemented using the codec's decoder            method and are included in the list entries.             sizehint, if given, is ignored since there is no efficient            way 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 recover            from decoding errors.         """        self.bytebuffer = ""        self.charbuffer = u""        self.linebuffer = None     def seek(self, offset, whence=0):        """ Set the input stream's current position.             Resets the codec buffers used for keeping state.        """        self.reset()        self.stream.seek(offset, whence)     def next(self):         """ Return the next decoded line from the input stream."""        line = self.readline()        if line:            return line        raise StopIteration     def __iter__(self):        return self     def __getattr__(self, name,                    getattr=getattr):         """ Inherit all other methods from the underlying stream.        """        return getattr(self.stream, name)     def __enter__(self):        return self     def __exit__(self, type, value, tb):        self.stream.close() ### class StreamReaderWriter:     """ StreamReaderWriter instances allow wrapping streams which        work in both read and write modes.         The design is such that one can use the factory functions        returned by the codec.lookup() function to construct the        instance.     """    # Optional attributes set by the file wrappers below    encoding = '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 classes            providing the StreamReader, StreamWriter interface resp.             Error handling is done in the same way as defined for the            StreamWriter/Readers.         """        self.stream = stream        self.reader = Reader(stream, errors)        self.writer = Writer(stream, errors)        self.errors = errors     def 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 self.reader.next()     def __iter__(self):        return self     def 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 __getattr__(self, name,                    getattr=getattr):         """ Inherit all other methods from the underlying stream.        """        return getattr(self.stream, name)     # these are needed to make "with codecs.open(...)" work properly     def __enter__(self):        return self     def __exit__(self, type, value, tb):        self.stream.close() ### class StreamRecoder:     """ StreamRecoder instances provide a frontend - backend        view of encoding data.         They use the complete set of APIs returned by the        codecs.lookup() function to implement their task.         Data written to the stream is first decoded into an        intermediate format (which is dependent on the given codec        combination) and then written to the stream using an instance        of the provided Writer class.         In the other direction, data is read from the stream using a        Reader instance and then return encoded data to the caller.     """    # Optional attributes set by the file wrappers below    data_encoding = 'unknown'    file_encoding = 'unknown'     def __init__(self, stream, encode, decode, Reader, Writer,                 errors='strict'):         """ Creates a StreamRecoder instance which implements a two-way            conversion: encode and decode work on the frontend (the            input to .read() and output of .write()) while            Reader and Writer work on the backend (reading and            writing to the stream).             You can use these objects to do transparent direct            recodings from e.g. latin-1 to utf-8 and back.             stream must be a file-like object.             encode, decode must adhere to the Codec interface, Reader,            Writer must be factory functions or classes providing the            StreamReader, StreamWriter interface resp.             encode and decode are needed for the frontend translation,            Reader and Writer for the backend translation. Unicode is            used as intermediate encoding.             Error handling is done in the same way as defined for the            StreamWriter/Readers.         """        self.stream = stream        self.encode = encode        self.decode = decode        self.reader = Reader(stream, errors)        self.writer = Writer(stream, errors)        self.errors = errors     def read(self, size=-1):         data = self.reader.read(size)        data, bytesencoded = self.encode(data, self.errors)        return data     def 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 data     def readlines(self, sizehint=None):         data = self.reader.read()        data, bytesencoded = self.encode(data, self.errors)        return data.splitlines(1)     def next(self):         """ Return the next decoded line from the input stream."""        data = self.reader.next()        data, bytesencoded = self.encode(data, self.errors)        return data     def __iter__(self):        return self     def write(self, data):         data, bytesdecoded = self.decode(data, self.errors)        return self.writer.write(data)     def writelines(self, list):         data = ''.join(list)        data, bytesdecoded = self.decode(data, self.errors)        return self.writer.write(data)     def reset(self):         self.reader.reset()        self.writer.reset()     def __getattr__(self, name,                    getattr=getattr):         """ Inherit all other methods from the underlying stream.        """        return getattr(self.stream, name)     def __enter__(self):        return self     def __exit__(self, type, value, tb):        self.stream.close() ### Shortcuts def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):     """ Open an encoded file using the given mode and return        a wrapped version providing transparent encoding/decoding.         Note: The wrapped version will only accept the object format        defined by the codecs, i.e. Unicode objects for most builtin        codecs. Output is also codec dependent and will usually be        Unicode as well.         Files are always opened in binary mode, even if no binary mode        was specified. This is done to avoid data loss due to encodings        using 8-bit values. The default file mode is 'rb' meaning to        open the file in binary read mode.         encoding specifies the encoding which is to be used for the        file.         errors may be given to define the error handling. It defaults        to 'strict' which causes ValueErrors to be raised in case an        encoding error occurs.         buffering has the same meaning as for the builtin open() API.        It defaults to line buffered.         The returned wrapped file object provides an extra attribute        .encoding which allows querying the used encoding. This        attribute is only available if an encoding was specified as        parameter.     """    if encoding is not None and \       'b' not in mode:        # Force opening of the file in binary mode        mode = mode + 'b'    file = __builtin__.open(filename, mode, buffering)    if encoding is None:        return file    info = lookup(encoding)    srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)    # Add attributes to simplify introspection    srw.encoding = encoding    return srw def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):     """ Return a wrapped version of file which provides transparent        encoding translation.         Strings written to the wrapped file are interpreted according        to the given data_encoding and then written to the original        file as string using file_encoding. The intermediate encoding        will usually be Unicode but depends on the specified codecs.         Strings are read from the file using file_encoding and then        passed back to the caller as string 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 'strict' which causes ValueErrors to be raised in case an        encoding error occurs.         The returned wrapped file object provides two extra attributes        .data_encoding and .file_encoding which reflect the given        parameters of the same name. The attributes can be used for        introspection by Python programs.     """    if file_encoding is None:        file_encoding = data_encoding    data_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 introspection    sr.data_encoding = data_encoding    sr.file_encoding = file_encoding    return sr ### Helpers for codec lookup def getencoder(encoding):     """ Lookup up the codec for the given encoding and return        its encoder function.         Raises a LookupError in case the encoding cannot be found.     """    return lookup(encoding).encode def getdecoder(encoding):     """ Lookup up the codec for the given encoding and return        its decoder function.         Raises a LookupError in case the encoding cannot be found.     """    return lookup(encoding).decode def getincrementalencoder(encoding):     """ Lookup up the codec for the given encoding and return        its IncrementalEncoder class or factory function.         Raises a LookupError in case the encoding cannot be found        or the codecs doesn't provide an incremental encoder.     """    encoder = lookup(encoding).incrementalencoder    if encoder is None:        raise LookupError(encoding)    return encoder def getincrementaldecoder(encoding):     """ Lookup up the codec for the given encoding and return        its IncrementalDecoder class or factory function.         Raises a LookupError in case the encoding cannot be found        or the codecs doesn't provide an incremental decoder.     """    decoder = lookup(encoding).incrementaldecoder    if decoder is None:        raise LookupError(encoding)    return decoder def getreader(encoding):     """ Lookup up the codec for the given encoding and return        its StreamReader class or factory function.         Raises a LookupError in case the encoding cannot be found.     """    return lookup(encoding).streamreader def getwriter(encoding):     """ Lookup up the codec for the given encoding and return        its StreamWriter class or factory function.         Raises a LookupError in case the encoding cannot be found.     """    return lookup(encoding).streamwriter def iterencode(iterator, encoding, errors='strict', **kwargs):    """    Encoding iterator.     Encodes the input strings from the iterator using a IncrementalEncoder.     errors and kwargs are passed through to the IncrementalEncoder    constructor.    """    encoder = getincrementalencoder(encoding)(errors, **kwargs)    for input in iterator:        output = encoder.encode(input)        if output:            yield output    output = encoder.encode("", True)    if output:        yield output def iterdecode(iterator, encoding, errors='strict', **kwargs):    """    Decoding iterator.     Decodes the input strings from the iterator using a IncrementalDecoder.     errors and kwargs are passed through to the IncrementalDecoder    constructor.    """    decoder = getincrementaldecoder(encoding)(errors, **kwargs)    for input in iterator:        output = decoder.decode(input)        if output:            yield output    output = decoder.decode("", True)    if output:        yield output ### Helpers for charmap-based codecs def make_identity_dict(rng):     """ make_identity_dict(rng) -> dict         Return a dictionary where elements of the rng sequence are        mapped to themselves.     """    res = {}    for i in rng:        res[i]=i    return res def make_encoding_map(decoding_map):     """ Creates an encoding map from a decoding map.         If a target mapping in the decoding map occurs multiple        times, then that target is mapped to None (undefined mapping),        causing an exception when encountered by the charmap codec        during translation.         One example where this happens is cp875.py which decodes        multiple character to \u001a.     """    m = {}    for k,v in decoding_map.items():        if not v in m:            m[v] = k        else:

Lines 501–1000 of 1034. Previous lines