Custom Python Charmap Codec

2019-02-28 06:03发布

I'm trying to write a custom Python codec. Here's a short example:

import codecs

class TestCodec(codecs.Codec):
    def encode(self, input_, errors='strict'):
        return codecs.charmap_encode(input_, errors, {
            'a': 0x01,
            'b': 0x02,
            'c': 0x03,
        })

    def decode(self, input_, errors='strict'):
        return codecs.charmap_decode(input_, errors, {
            0x01: 'a',
            0x02: 'b',
            0x03: 'c',
        })

def lookup(name):
    if name != 'test':
        return None
    return codecs.CodecInfo(
        name='test',
        encode=TestCodec().encode,
        decode=TestCodec().decode,
    )

codecs.register(lookup)
print(b'\x01\x02\x03'.decode('test'))
print('abc'.encode('test'))

Decoding works, but encoding throws an exception:

$ python3 codectest.py
abc
Traceback (most recent call last):
  File "codectest.py", line 29, in <module>
    print('abc'.encode('test'))
  File "codectest.py", line 8, in encode
    'c': 0x03,
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-2:
character maps to <undefined>

Any ideas how to use charmap_encode properly?

1条回答
Lonely孤独者°
2楼-- · 2019-02-28 06:31

Look at https://docs.python.org/3/library/codecs.html#encodings-and-unicode (third paragraph), take the hint to look at encodings/cp1252.py, and check out the following code:

import codecs

class TestCodec(codecs.Codec):
    def encode(self, input_, errors='strict'):
        return codecs.charmap_encode(input_, errors, encoding_table)

    def decode(self, input_, errors='strict'):
        return codecs.charmap_decode(input_, errors, decoding_table)

def lookup(name):
    if name != 'test':
        return None
    return codecs.CodecInfo(
        name='test',
        encode=TestCodec().encode,
        decode=TestCodec().decode,
    )

decoding_table = (
    'z'
    'a'
    'b'
    'c'
)    
encoding_table=codecs.charmap_build(decoding_table)
codecs.register(lookup)

### --- following is test/debug code
print(ascii(encoding_table))

print(b'\x01\x02\x03'.decode('test'))
foo = 'abc'.encode('test')
print(ascii(foo))

Output:

{97: 1, 122: 0, 99: 3, 98: 2}
abc
b'\x01\x02\x03'
查看更多
登录 后发表回答