python zlib 库是否支持 uuencode



我的python代码正在尝试使用zlib库解压缩uuen编码的文件。以下是代码片段:

self.decompress = zlib.decompressobj(wbits)
.
.
buf = self.fileobj.read(size)
.
.
uncompress = self.decompress.decompress(buf)

我目前对 wbits 的值是 '-zlib。MAX_WBITS'。这将引发错误:

Error -3 while decompressing: invalid literal/lengths set

我意识到python zlib库支持:

RFC 1950 (zlib compressed format)
RFC 1951 (deflate compressed format)
RFC 1952 (gzip compressed format)

WBITS的选择是:

to (de-)compress deflate format, use wbits = -zlib.MAX_WBITS
to (de-)compress zlib format, use wbits = zlib.MAX_WBITS
to (de-)compress gzip format, use wbits = zlib.MAX_WBITS | 16

所以我的问题是:

Where does a uuencoded file fall in this list?
Is it supported by zlib?
If yes, what should be the value for wbits?
If no, how do I proceed with this?

提前感谢!

下面是如何使用 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

输出

begin 666 <data>
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
True

上面的代码仅适用于Python 2。Python 3 明确区分了文本和字节,它不支持字节字符串的编码或文本字符串的解码。所以它不能使用上面显示的简单uuencoding/uudecode技术。

这是一个适用于 Python2 和 Python 3 的新版本。

from __future__ import print_function
import zlib
import uu
from io import BytesIO
def zlib_uuencode(databytes, name='<data>'):
    ''' 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 <data>
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_uuencodezlib_uuencode 处理bytes字符串:您必须向它们传递一个bytes参数,它们会返回一个bytes结果。

最新更新