Python 2.7:使用“ lzma”模块以XZ格式压缩数据

ki2*_*2ne 6 python checksum lzma xz

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

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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

# 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"
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*son 6

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

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

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
Run Code Online (Sandbox Code Playgroud)

这将test.txt使用xz命令行实用程序和Python模块压缩文件,然后比较结果。在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库制作有效的压缩文件。