下面是一个快速演示如何使用zlib压缩并使用uuencode进行编码,然后反转过程。在#!/usr/bin/env python
import zlib
data = '''This is a short piece of test data
intended to test uuencoding and decoding
using the uu module, and compression and
decompression using zlib.
'''
data = data * 5
# encode
enc = zlib.compress(data, 9).encode('uu')
print enc
# decode
dec = zlib.decompress(enc.decode('uu'))
#print `dec`
print dec == data
输出
^{pr2}$
上面的代码只适用于python2。python3在文本和字节之间进行了明确的分隔,它不支持字节字符串的编码,也不支持文本字符串的解码。所以它不能使用上面所示的简单的uuencoding/uudeconding技术。在
这是一个可以同时在Python2和python3上运行的新版本。在from __future__ import print_function
import zlib
import uu
from io import BytesIO
def zlib_uuencode(databytes, name=''):
''' Compress databytes with zlib & uuencode the result '''
inbuff = BytesIO(zlib.compress(databytes, 9))
outbuff = BytesIO()
uu.encode(inbuff, outbuff, name=name)
return outbuff.getvalue()
def zlib_uudecode(databytes):
''' uudecode databytes and decompress the result with zlib '''
inbuff = BytesIO(databytes)
outbuff = BytesIO()
uu.decode(inbuff, outbuff)
return zlib.decompress(outbuff.getvalue())
# Test
# Some plain text data
data = '''This is a short piece of test data
intended to test uuencoding and decoding
using the uu module, and compression and
decompression using zlib.
'''
# Replicate the data so the compressor has something to compress
data = data * 5
#print(data)
print('Original length:', len(data))
# Convert the text to bytes & compress it.
databytes = data.encode()
enc = zlib_uuencode(databytes)
enc_text = enc.decode()
print(enc_text)
print('Encoded length:', len(enc_text))
# Decompress & verify that it's correct
dec = zlib_uudecode(enc)
print(dec == databytes)
输出Original length: 720
begin 666
M>-KMCLL-A# ,1.^I8@I 5$,#(?822V C[%RV>CXY; %[19K+/,U(;ZKBN)+A
MU8[ +EP8]D&P!RA'3J+!2DP(Z[0UUF(DNB K@;B7U/Q&4?E:8#-J*P_/HMBV
;'^PNID]/]^6'^N^[RCRFZ?5Y??[P.0$_I03L
end
Encoded length: 185
True
请注意,zlib_uuencode和zlib_uuencode处理bytes字符串:必须向它们传递一个bytes参数,它们返回bytes结果。在