关于校验和:Python 2.7:使用“ lzma”模块以XZ格式压缩数据

Python 2.7: Compressing data with the XZ format using the “lzma” module

我正在使用Python 2.7.6中的lzma模块进行实验,以查看是否可以为将来的项目使用XZ格式创建压缩文件。 我在实验期间使用的代码是:

1
2
3
4
5
6
7
8
9
import lzma as xz

in_file = open('/home/ki2ne/Desktop/song.wav', 'rb')
input_data = in_file.read()

compressed_data = xz.compress(input_data)
out_file = open('/home/ki2ne/Desktop/song.wav.xz', 'wb')
in_file.close()
out_file.close()

与使用普通xz时相比,我注意到生成的文件中有两个不同的校验和(MD5和SHA256)(尽管我可以用两种方法解压缩-两个文件的解压缩版本的校验和都相同)。 这会是个问题吗?

更新:我找到了一个修复程序,方法是通过peterjc的Git存储库(从此处链接)安装backport(来自Python 3.3),现在它显示相同的校验和。 不确定是否有帮助,但是我确保未安装存储库中的LZMA Python模块,以避免可能的名称冲突。

这是我的测试代码以确认这一点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# I have created two identical text files with some random phrases

from subprocess import call
from hashlib import sha256
from backports import lzma as xz

f2 = open("test2.txt" , 'rb')
f2_buf = buffer(f2.read())
call(["xz","test1.txt"])

f2_xzbuf = buffer(xz.compress(f2_buf))
f1 = open("test1.txt.xz", 'rb')
f1_xzbuf = buffer(f1.read())

f1.close(); f2.close()

f1sum = sha256(); f2sum = sha256()

f1sum.update(f1_xzbuf); f2sum.update(f2_xzbuf)

if f1sum.hexdigest() == f2sum.hexdigest():
    print"Checksums OK"
else:
    print"Checksum Error"

我还使用常规的sha256sum进行了验证(当我将数据写入文件时)。


我不会担心压缩文件的差异-根据容器格式和.xz文件中使用的校验和类型,压缩数据可以变化而不会影响内容。

编辑我一直在进一步研究这个问题,并编写了此脚本来测试PyLZMA Python2.x模块和内置模块中的lzma Python3.x

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from __future__ import print_function
try:
    import lzma as xz
except ImportError:
    import pylzma as xz
import os

# compress with xz command line util
os.system('xz -zkf test.txt')

# now compress with lib
with open('test.txt', 'rb') as f, open('test.txt.xzpy', 'wb') as out:
    out.write(xz.compress(bytes(f.read())))

# compare the two files
from hashlib import md5

with open('test.txt.xz', 'rb') as f1, open('test.txt.xzpy', 'rb') as f2:
    hash1 = md5(f1.read()).hexdigest()
    hash2 = md5(f2.read()).hexdigest()
    print(hash1, hash2)
    assert hash1 == hash2

这将使用xz命令行实用程序和Python模块压缩文件test.txt,并比较结果。在Python3下,lzma产生与xz相同的结果,但是在Python2下,PyLZMA产生不同的结果,该结果无法使用xz命令行util提取。

您正在使用哪个模块在Python2中称为" lzma",并且使用了什么命令来压缩数据?

编辑2好的,我找到了Python2的pyliblzma模块。但是,它似乎使用CRC32作为默认的校验和算法(其他人使用CRC64),并且存在一个错误阻止更改校验和算法https://bugs.launchpad.net/pyliblzma/+bug/1243344

您可以尝试使用xz -C crc32进行压缩以比较结果,但是我仍然无法使用Python2库制作有效的压缩文件。


在我的情况下(Ubuntu / Mint),为了在Pyhton 2.7中使用lzma模块,我直接与pip(我没有使用过github),sudo或root用户一起安装backports.lzma

1
pip2 install backports.lzma

FYI pip2具有--user选项,该选项不需要超级用户权限,并且仅为本地用户安装模块,但是我尚未对此进行测试。

除了执行pip安装之外,还必须使用包管理器安装一个强制性依赖项:库liblzma

在我的情况下,软件包名称是liblzma5liblzma-dev,但是Linux发行版/发行版之间的软件包名称可能有所不同。

P.s:在不同的Linux环境(未知集群发行版)上,我还成功地使用conda重复了相同的操作:

1
2
conda install backports
conda install backports.lzma --name pyEnvName

希望有用