Exemplo n.º 1
0
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
    """ Return a wrapped version of file which provides transparent
        encoding translation.

        Data written to the wrapped file is decoded according
        to the given data_encoding and then encoded to the underlying
        file using file_encoding. The intermediate data type
        will usually be Unicode but depends on the specified codecs.

        Bytes read from the file are decoded using file_encoding and then
        passed 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 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
Exemplo n.º 2
0
    def _test_incrementalencoder(self):
        import _multibytecodec, _codecs, _io
        with open(self.myfile + '/shift_jis.txt', 'rb') as fid:
            uni_str =  fid.read()
        with open(self.myfile + '/shift_jis-utf8.txt', 'rb') as fid:
            utf8str =  fid.read()
        UTF8Reader = _codecs.lookup('utf-8').streamreader
        for sizehint in [None] + list(range(1, 33)) + \
                        [64, 128, 256, 512, 1024]:
            istream = UTF8Reader(_io.BytesIO(utf8str))
            ostream = _io.BytesIO()
            codec = _multibytecodec.__getcodec('cp932')
            print(dir(codec))
            encoder = codec.incrementalencoder()
            while 1:
                if sizehint is not None:
                    data = istream.read(sizehint)
                else:
                    data = istream.read()

                if not data:
                    break
                e = encoder.encode(data)
                ostream.write(e)
            assert ostream.getvalue() == uni_str
Exemplo n.º 3
0
 def test_cp20302(self):
     import _codecs
     for encoding in ip_supported_encodings:
         if encoding.lower() in [
                 'cp1252'
         ]:  #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20302
             continue
         temp = _codecs.lookup(encoding)
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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
Exemplo n.º 6
0
def test_codecs_lookup():
    l = []
    def my_func(encoding, cache = l):
        l.append(encoding)
    
    codecs.register(my_func)
    allchars = ''.join([chr(i) for i in xrange(1, 256)])
    try:
        codecs.lookup(allchars)
        AssertUnreachable()
    except LookupError:
        pass
        
    lowerchars = allchars.lower().replace(' ', '-')
    for i in xrange(1, 255):
        if l[0][i] != lowerchars[i]:
            Assert(False, 'bad chars at index %d: %r %r' % (i, l[0][i], lowerchars[i]))
            
    AssertError(TypeError, codecs.lookup, '\0')
    AssertError(TypeError, codecs.lookup, 'abc\0')
    AreEqual(len(l), 1)
Exemplo n.º 7
0
def test_codecs_lookup():
    l = []
    def my_func(encoding, cache = l):
        l.append(encoding)
    
    codecs.register(my_func)
    allchars = ''.join([chr(i) for i in xrange(1, 256)])
    try:
        codecs.lookup(allchars)
        AssertUnreachable()
    except LookupError:
        pass
        
    lowerchars = allchars.lower().replace(' ', '-')
    for i in xrange(1, 255):
        if l[0][i] != lowerchars[i]:
            Assert(False, 'bad chars at index %d: %r %r' % (i, l[0][i], lowerchars[i]))
            
    AssertError(TypeError, codecs.lookup, '\0')
    AssertError(TypeError, codecs.lookup, 'abc\0')
    AreEqual(len(l), 1)
Exemplo n.º 8
0
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
Exemplo n.º 9
0
def open(filename, mode='r', 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.

        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 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 = builtins.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
Exemplo n.º 10
0
def test_cp20302():
    import _codecs
    for encoding in ip_supported_encodings:
        if encoding.lower() in ['cp1252']: #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20302
            continue
        temp = _codecs.lookup(encoding)
Exemplo n.º 11
0
def _lookup_text_encoding(encoding, alternate_command):
    codec_info = _codecs.lookup(encoding)
    if not isinstance(codec_info, tuple) or not codec_info._is_text_encoding:
        raise LookupError("'%s' is not a text encoding; use %s to handle arbitrary codecs" % (encoding, alternate_command))
    return codec_info
Exemplo n.º 12
0
 def test_cp20302(self):
     import _codecs
     for encoding in ip_supported_encodings:
         _codecs.lookup(encoding)