如何在Python中创建整个存储单元的压缩存档?

时间:2018-04-17 08:20:45

标签: python-3.x

我想使用Python3脚本创建eMMC(具有多个主分区)的压缩备份。我想模仿管道ddbzip2xz的输出的行为。我尝试了以下两种方法:

增量压缩器

import bz2
import time
import binascii

compressor = bz2.BZ2Compressor()

with open('/dev/mmcblk0', 'rb') as src_handle:
    with open('/media/usb0/backup_emmc.bz2', 'wb') as dest_handle:
        last_check = time.time()
        read = 0
        written = 0
        chunksize_bytes = 10485760  # 10 MB
        while True:
            input = src_handle.read(chunksize_bytes)
            if not input:
                print("Flushing remaining data")
                remaining_data = compressor.flush()
                dest_handle.write(binascii.hexlify(remaining_data))
                print("Copying complete")
                break
            else:
                written += dest_handle.write(binascii.hexlify(compressor.compress(input)))
                if time.time() - last_check >= 1:
                    last_check = time.time()
                    print("Read {:.2f} MB".format(read / (1024.0**2)))
                    print("Written {:.2f} MB".format(written / (1024.0**2)))
                read += chunksize_bytes

写入压缩文件

import bz2
import shutil
with open('/dev/mmcblk0', 'rb') as src_handle:
    with bz2.BZ2File('/media/usb0/backup_emmc.bz2', 'wb', compresslevel=9) as dest_handle:
        shutil.copyfileobj(src_handle, dest_handle)

这两种方法都会生成一个小文件,它不可能是由我的整个eMMC构成的压缩存档。当我使用bzip2dd进行复制时,存储的内容将不再可读。除了通过子进程使用bash实用程序之外,这样做的正确pythonic方法是什么?

0 个答案:

没有答案