使用带有 LZMA 压缩的 `tarfile` 时如何设置压缩级别?

How to set compression level while using `tarfile` with LZMA compression?

在使用 Python 中的 tarfile 模块为 LZMA (*.xz) 压缩创建存档时,是否可以设置压缩级别?

我正在使用以下构造,我想知道 tarfile.open 方法的 compresslevel 关键字参数是否也适用于 LZMA 压缩?

tarfile.open(tar_file_path, 'w:xz', compresslevel=9) as tf:
    ...

The documentation 对此有点无益...

看起来 'compresslevel' 不是 'tarfile' 中的一个选项。

使用 'lzma' 模块是可能的。

The compression settings can be specified either as a preset compression level (with the preset argument), or in detail as a custom filter chain (with the filters argument).

The preset argument (if provided) should be an integer between 0 and 9 (inclusive), optionally OR-ed with the constant PRESET_EXTREME. If neither preset nor filters are given, the default behavior is to use PRESET_DEFAULT (preset level 6). Higher presets produce smaller output, but make the compression process slower.

import lzma
my_filters = [
    {"id": lzma.FILTER_DELTA, "dist": 5},
    {"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME},
]
with lzma.open("file.xz", "w", filters=my_filters) as f:
    f.write(b"blah blah blah")

请检查Compression using the LZMA algorithm