Skip to main content

Pure python 7-zip library

Reason this release was yanked:

malware test case

Project description

logo py7zr – a 7z library on python

https://readthedocs.org/projects/py7zr/badge/?version=latest https://badge.fury.io/py/py7zr.svg https://travis-ci.com/miurahr/py7zr.svg?branch=master https://github.com/miurahr/py7zr/workflows/Run%20Tox%20tests/badge.svg https://dev.azure.com/miurahr/github/_apis/build/status/miurahr.py7zr?branchName=master https://coveralls.io/repos/github/miurahr/py7zr/badge.svg?branch=master

py7zr is a library and utility to support 7zip archive compression, decompression, encryption and decryption written by Python programming language.

Install

You can install py7zr as usual other libraries using pip.

$ pip install py7zr

When you want to handle extra codecs (ZStandard) then add extra requirements to command line

$ pip install py7zr[zstd]

Documents

User manuals

Developer guide

CLI Usage

You can run command script py7zr like as follows;

  • List archive contents

$ py7zr l test.7z
  • Extract archive

$ py7zr x test.7z
  • Extract archive with password

$ py7zr x -P test.7z
  password?: ****
  • Create and compress to archive

$ py7zr c target.7z test_dir
  • Create multi-volume archive

$ py7zr c -v 500k target.7z test_dir
  • Test archive

$ py7zr t test.7z
  • Show information

$ py7zr i
  • Show version

$ py7zr --version

SevenZipFile Class Usage

py7zr is a library which can use in your python application.

Decompression/Decryption

Here is a code snippet how to decompress some file in your application.

import py7zr

archive = py7zr.SevenZipFile('sample.7z', mode='r')
archive.extractall(path="/tmp")
archive.close()

You can also use ‘with’ block because py7zr provide context manager(v0.6 and later).

import py7zr

with py7zr.SevenZipFile('sample.7z', mode='r') as z:
    z.extractall()

with py7zr.SevenZipFile('target.7z', 'w') as z:
    z.writeall('./base_dir')

py7zr also supports extraction of single or selected files by ‘extract(targets=[‘file path’])’. Note: if you specify only a file but not a parent directory, it will fail.

import py7zr
import re

filter_pattern = re.compile(r'<your/target/file_and_directories/regex/expression>')
with SevenZipFile('archive.7z', 'r') as archive:
    allfiles = archive.getnames()
    selective_files = [f if filter_pattern.match(f) for f in allfiles]
    archive.extract(targets=selective_files)

py7zr support an extraction of password protected archive.(v0.6 and later)

import py7zr

with py7zr.SevenZipFile('encrypted.7z', mode='r', password='secret') as z:
    z.extractall()

Compression/Encryption

Here is a code snippet how to produce archive.

import py7zr

with py7zr.SevenZipFile('target.7z', 'w') as archive:
    archive.writeall('/path/to/base_dir', 'base')

To create encrypted archive, please pass a password.

import py7zr

with py7zr.SevenZipFile('target.7z', 'w', password='secret') as archive:
    archive.writeall('/path/to/base_dir', 'base')

To create archive with algorithms such as zstandard, you can call with custom filter.

import py7zr

my_filters = [{"id": py7zr.FILTER_ZSTD}]
another_filters = [{"id": py7zr.FILTER_ARM}, {"id": py7zr.FILTER_LZMA2, "preset": 7}]
with py7zr.SevenZipFile('target.7z', 'w', filters=my_filter) as archive:
    archive.writeall('/path/to/base_dir', 'base')

shutil helper

py7zr also support shutil interface.

from py7zr import pack_7zarchvie, unpack_7zarchive
import shutil

# register file format at first.
shutil.register_archive_format('7zip', pack_7zarchive, description='7zip archive')
shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)

# extraction
shutil.unpack_archive('test.7z', '/tmp')

# compression
shutil.make_archive('target', '7zip', 'src')

Required Python versions

py7zr uses a python3 standard lzma module for extraction and compression. The standard lzma module uses liblzma that support core compression algorithm of 7zip.

Minimum required version is Python 3.5. Two additional library is required only on Python3.5; contextlib2 and pathlib2.

Compression is supported on Python 3.6 and later. Multi-volume archive creation issupported on Python 3.7 and later.

There are other runtime requrements; texttable, pycryptodome

Version recommendations are:

  • CPython 3.7.5, CPython 3.8.0 and later.

  • PyPy3.6-7.2.0 and later.

Following fixes are included in these versions, and it is not fixed on python3.6.

  • BPO-21872: LZMA library sometimes fails to decompress a file

  • PyPy3-3088: lzma.LZMADecomporessor.decompress does not respect max_length

Compression Methods supported

‘py7zr’ supports algorithms and filters which lzma module and liblzma support. It also support BZip2 and Deflate that are implemented in python core libraries, and ZStandard with third party libraries. py7zr, python3 core lzma module and liblzma do not support some algorithms such as PPMd, BCJ2 and Deflate64.

Here is a table of algorithms.

#

Category

Algorithm combination

1

  • Compression

  • Decompression

LZMA2 + Delta or BCJ(X86, ARM, PPC, IA64, ARMT, SPARC)

2

LZMA + BCJ(X86,ARMT,ARM,PPC,SPARC)

3

LZMA2, LZMA, Bzip2, Deflate, COPY

4

Bzip2,Deflate + BCJ(X86,ARM,PPC,ARMT,SPARC)

6

  • Encryption

  • Decryption

7zAES + LZMA2 + Delta or BCJ

6

7zAES + LZMA

7

7zAES + Bzip2, Deflate

8

  • Compression only

LZMA + BCJ(IA64)

9

  • Unsupported

PPMd, BCJ2, Deflate64

10

ZStandard

  • A feature handling symbolic link is basically compatible with ‘p7zip’ implementation, but not work with original 7-zip because the original does not implement the feature.

  • Decryption of filename encrypted archive is also supported.

  • CAUTION: Specifying an unsupported algorithm combination may produce a broken archive.

  • ZStandard support is under development, but not working yet.

Use Cases

  • aqtinstall Another (unofficial) Qt (aqt) CLI Installer on multi-platforms.

  • PreNLP Preprocessing Library for Natural Language Processing

  • mlox a tool for sorting and analyzing Morrowind plugin load order

License

  • Copyright (C) 2019,2020 Hiroshi Miura

  • pylzma Copyright (c) 2004-2015 by Joachim Bauch

  • 7-Zip Copyright (C) 1999-2010 Igor Pavlov

  • LZMA SDK Copyright (C) 1999-2010 Igor Pavlov

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

Py7zr ChangeLog

All notable changes to this project will be documented in this file.

Unreleased

Added

Changed

Fixed

Deprecated

Removed

Security

v0.9.10

Security

  • Drop issue_218.7z test data wihch is reported a blackmoon trojan(#285)

v0.9.9

Fixed

  • (backport) Fix BCJ filter issue failing a certain data when LZMA+BCJ compression(#240, #250)

v0.9.8

Changed

  • Avoid re-read header data from fike, otherwise calculate CRC32 when writing header.(#246)

v0.9.7

Fixed

  • Raise PasswordRequired when encrypted header and no password given(#238)

v0.9.6

Fixed

  • CLI: Catch exception when currupted data or wrong password(#230)

v0.9.5

Fixed

  • Catch exception in threading extraction(#218, #220)

v0.9.4

Changed

  • Raise ‘PasswordRequired’ exception when no password given for encrypted archive (#215, #216)

v0.9.3

Fixed

  • Support COPY compression method.

Changed

  • ZStandard compression/decompression handle property.

v0.9.2

Changed

  • Utilize max_length argument for each decompressor.(#210, #211)

  • Change READ_BUFFER_SIZE 32768 for python 3.7.5 and before.

  • Extend Buffer size when necessary.(#209)

v0.9.1

Changed

  • Improve DecompressionChain.decompress() logics.(#207)

Fixed

  • Fix BCJ filter for decompression that can cause infinite loop or wrong output.(#204,#205,#206)

v0.9.0

Added

  • BCJ Decoder/Encoder written by python.(#198, #199)

  • Support Bzip2, Defalte + BCJ(X86, PPC, ARM, ARMT, SPARC) (#199)

  • Add Copy method as an extraction only support.(#184)

Changed

  • Use large(1MB) read blocksize for Python 3.7.5 and later and PyPy 7.2.0 and later.

  • Set ZStandard compression as unsupported because of a bug with unknown reason.(#198)

  • Manage compression methods to handle whether decompressor requires coder[‘property’] or not.

Fixed

  • Significantly improve decompress performance which is as same speed as v0.7.*. by updating buffer handling.

  • Fix decompression max_size to pass lzma module. Now it is as same as out_remaining.

  • Support LZMA+BCJ(X86, PPC, ARM, ARMT, SPARC) with alternative BCJ filter.(#198, #199)

  • Fix packinfo crc read and write (#187, #189)

  • Accept archive which Method ID is NULL(size=0)(#181, #182)

  • CLI: Does not crash when trying extract archive which use unsupported method(#183)

v0.8.0

Added

  • test: add test for #178 bug report the case of LZMA+BCJ as xfails.

  • File format specification: add ISO/IEC standard style specification document.

  • Support extra methods for archiveinfo() method.(#150)

  • test: unit tests for Sparc, ARMT and IA64 filters.

  • Support for PPC and ARM filters.

  • Support encryption(#145)

  • Export supported filter constants, such as FILTER_ZSTD(#145)

Changed

  • Improve README, documents and specifications.

  • Update password handling and drop get_password() helper (#162)

  • Enable encoded header and add more test with 7zip compatibility.(#164)

  • Refactoring SevenZipFile class internals. (#160)

  • Refactoring classes in compressor module. (#161)

  • Add ‘packinfo.crcs’ field digests data when creating archive.(#157) It help checking archive integrity without extraction.

  • CLI: help option to show py7zr version and python version.

  • Use importlib for performance improvement instead of pkg_resources module.

  • Documents: additional methods, filter examples.

  • CI configurations: Manage coverage with Coveralls.

  • Refactoring decompression classes to handle data precisely with folder.unpacksizes(#146)

  • Default compression mode is LZMA2+BCJ which is as same as 7zip and p7zip(#145)

  • Enhance encryption strength, IV is now 16 bytes, and generated with cryptodom.random module.(#145)

  • Refactoring compression algorythm related modules.

Fixed

  • Now return correct header size by archiveinfo() method.(#169)

  • Disable adding CRC for encoded header packinfo.(#164)

  • Fix password leak/overwrite among SevenZipFile objects in a process.(#159) This can cause decryption error or encryption with unintended password.

  • Release password on close()

  • SevenZipFile.test() method now working properly. (#155)

  • Fix extraction error on python 3.5.(#151)

  • Support combination of filters(#145)

  • Compression of Delta, BZip2, ZStandard, and Deflate(#145)

  • Fix archived head by multiple filter specified.

  • Fix delta filter.

  • Working with BCJ filter.

  • Fix archiveinfo to provide proper names.

Removed

  • test: Drop some test case with large files.

  • Drop ArchiveProperty class: A field has already deprecated or not used.(#170)

  • Drop AntiFile property: a property has already deprecated or not used.

  • remove final_header definition.

v0.7.3

Added

  • Support for encrypted header (#139, #140)

Changed

  • Fix CRC32 check and introduce test and testzip methods (#138)

Fixed

  • Allow decryption of data which is encrypted without any compression.(#140)

v0.7.2

Added

  • CLI: ‘-v {size}[b|k|m|g]’ multi volume creation option.

v0.7.1

Changed

  • Decryption: performance improvement. Introduce helpers.calculate_key3(), which utilize list comprehension expression, bytes generation with join(). It reduces a number of calls of hash library and improve decryption performance.

Fixed

  • Fix overwrite behavior of symbolic link which may break linked contents.

v0.7.0

Added

  • Support dereference option of SevenZipFile class. (#131) If dereference is False, add symbolic and hard links to the archive. If it is True, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links.

  • Introduce progress callback mechanism (#130)

  • Support memory API.(#111, #119) Introduce read(filter) and readall() method for SevenZipFile class.

  • Support ZStandard codec compression algorithm for extraction.(#124, #125)

Changed

  • Extraction: Unlink output file if exist when it become a symbolic link. When overwrite extracted files and there are symlinks, it may cause an unexpected result. Unlinking it may help it.

  • CLI: add –verbose option for extraction

  • win32: update win32compat

  • Drop pywin32 dependency(#120)

  • Introduce internal win32compat.py

  • Archive: Looking for symbolic link object in the archived list, and if found, record as relative link.(#112, #113, #122)

Fixed

  • Fix archiveinfo() for 7zAES archives

  • Release variables when close() (#129)

  • Support extraction of file onto a place where path length is > 260 bytes on Windows 10, Windows Server 2016R2 and later. (Windows Vista, 7 and Windows Server 2012 still have a limitation of path length as a OS spec)(#116, #126)

Removed

  • Revmoed requirements.txt. When you want to install dependencies for development you can do it with ‘pip install -e path/to/py7zr_project’

v0.6

Added

  • Test: SevenZipFile.archiveinfo() for various archives.

  • Test: extraction of LZMA+BCJ archive become fails as marked known issue.

  • Support deflate decompression method.

  • Introduce context manager for SevenZipFile (#95)

  • Test: add benchmarking test.

  • Add concurrent extraction test.

  • Add remote data test for general application test.

  • Add class for multi volume header.

  • Add readlink helper function for windows.

  • Test: download and extract test case as a show case.

  • setup.cfg: add entry-point configuration.

  • Support filtering a target of extracted files from archive (#64)

  • Support decryption (#55)

  • Add release note automation workflow with Github actions.

  • COPY decompression method.(#61)

Changed

  • Update documents and README about supported algorithms.

  • Re-enable coverage report.

  • Refactoring SevenZipFile._write_archive() method to move core chunk into compression module Worker.archive() method.

  • Update calculate_key helper to improve performance.

  • Introduce zero-copy buffer helper.

  • Change decompressor class interface
    • change max_length type to int and defualt to -1.

  • Update decryption function to improve performance.

  • SevenZipFile(file-object, ‘r’) now can run extract() well even unlink before extract().

  • Concurrency strategy: change to threading instead of multiprocessing. (#92)

  • Release process is done by Github Actions

  • Temporary disable to measure coverage, which is not working with threading.

  • Tox: now pass PYTEST_ADDOPTS environment variable.

  • extract: decompression is done as another process in default.

  • extract: default multiprocessing mode is spawn

  • extract: single process mode for password protected archive.

  • Use spawn multiprocessing mode for all platforms.

  • Use self context for multiprocessing.

  • Concurrency implementation changes to use multiprocessing.Process() instead of concurrency.futures to avoid freeze or deadlock with application usage of it.(#70)

  • Stop checking coverage because coverage.py > 5.0.0 produce error when multiprocessing.Process() usage.

  • Drop handlers, NullHandler, BufferHnalder, and FileHander.

Fixed

  • Fix SevenZipFIle.archiveinfo() crash for LZMA+BCJ archive.(#100)

  • Fix SevenZipFile.test() method defeated from v0.6b2 (#103)

  • Fix SevenZipFile.solid() method to return proper value. (#72,#97)

  • Fix README example for extraction option.

  • Some of decryption of encrypted archive fails.(#75)

  • Make pywin32 a regular runtime dependency

  • Build with pep517 utility.

  • Fix race condition for changing current working directory of caller, which cause failures in multithreading.(#80,#82)

  • extract: catch UnsupportedMethod exception properly when multiprocessing.

  • Fixed extraction of 7zip file with BZip2 algorithm.(#66)

  • Fix symbolic link extraction with relative path target directory.(#67)

  • Fix retrieving Folder header information logics for codecs.(#62)

Security

  • CLI: Use ‘getpass’ standard library to input password.(#59)

Removed

  • Static py7zr binary. Now it is generated by python installer.

  • Test symlink on windows.(#60)

v0.5

Support making a 7zip archive.

Added

  • Support for compression and archiving.

  • Support encoded(compressed) header and set as default.(#39)

  • SevenZipFile: accept pathlib.Path as a file argument.

  • Unit test: read and write UTF-16LE string for filename.

  • Support for shutil.register_archive_format() and shutil.make_archive() by exposing pack_7zarchive()

  • Support custom filters for compression.

Changed

  • Update documents.

Fixed

  • Fix extraction of archive which has zero size files and directories(#54).

  • Revert zero size file logic(#47).

  • Revert zero size file logic which break extraction by 7zip.

  • Support for making archive with zero size files(#47).

  • Produced broken archive when target has many directorires(#48).

  • Reduce test warnings, fix annotations.

  • Fix coverage error on test.

  • Support for making archive with symbolic links.

  • Fix write logics (#42)

  • Fix read FilesInfo block.

  • Skip rare case when directory already exist, that can happen multiple process working in same working directory.

  • Write: Produce a good archive file for multiple target files.

  • SignatureHeader function: write nextheaderofs and nextheadersize as real_uint64.

  • docs: description of start header structure.

Removed

  • Drop py7zr.properties.FileAttributes; please use stat.FILE_ATTRIBUTES_*

Changed

  • Test: Use tmp_path fixture which is pytest default one.

  • Move setuptools configurations in setup.py into setup.cfg.

v0.4

Added

  • Support for pypy3 (pypy3.5-7.0) and later(pypy3.6-7.1 or later).

  • unit test for NullHandler, BufferHandler, FileHandler.

  • Update document to add 7zformat descriptions.

Changed

Fixed

  • Update README to indicate supported python version as 3.5 and later, pypy3 7.1 and later.

v0.3.5

Changed

  • Use seek&truncate for padding trailer if needed.

v0.3.4

Added

  • Docs: class diagram, design note, 7z formats and presentations.

  • Test for a target includes padding file.

Changed

  • Test file package naming.

Fixed

  • Fix infinite loop when archive file need padding data for extraction.

v0.3.3

Added

  • Add test for zerofile with multi-foler archive.

Fixed

  • Fix zerofile extraction error with multithread mode(#24, thanks @Arten013)

v0.3.2

Added

  • typing hints

  • CI test with mypy

  • Unit test: SignatureHeader.write() method.

  • Unit test: unknown mode for SevenZipFile constructor.

  • Unit test: SevenZipFile.write() method.

Changed

  • Conditional priority not likely to be external in header.

  • Refactoring read_uint64().

Fixed

  • SignatureHeader.write(): fix exception to write 7zip version.

v0.3.1

Added

  • CLI i subcommand: show codec information.

  • Decompression performance test as regression test.

  • Add more unit test for helper functions.

Changed

  • List subcommand now do not show compressed file size in solid compression. This is as same behavior as p7zip command.

  • Merge io.py into archiveinfo.py

  • Drop internal intermediate queue, which is not used.

Fixed

  • Always overwrite when archive has multiple file with same name.

v0.3

Added

  • Add some code related to support write feature(wip).

  • Static check for import order in python sources and MANIFEST.in

Changed

  • Concurrent decompression with threading when an archive is in multi folder compression.

  • Pytest configurations are set in tox.ini

Fixed

  • Package now has test code and data.

v0.2.0

Fixed

  • Detect race condition on os.mkdir

v0.1.6

Fixed

  • Wrong file size when lzma+bcj compression.

v0.1.5

Fixed

  • Suppress warning: not dequeue from queue length 0

v0.1.4

Changed

  • When a directory exist for target, do not raise error, and when out of it raise exception

  • Refactoring FileArchivesList and FileArchive classes.

v0.1.3

Changed

  • When a directory exist for target, do not raise error, and when out of it raise exception

v0.1.2

Changed

  • Refactoring CLI with cli package and class.

Fixed

  • Archive with zero size file cause exception with file not found error(#4).

Removed

  • Drop unused code chunks.

  • Drop Digests class and related unit test.

v0.1.1

Added

  • Add write(), close() and testzip() dummy methods which raises NotImplementedError.

  • Add more unit tests for write functions.

Fixed

  • Fix Sphinx error in documentation.

  • SevenZipFile: Check mode before touch file.

  • Fix write_boolean() when array size is over 8.

  • Fix write_uint64() and read_uint64().

v0.1.0

Added

  • Introduce compression package.

  • Introduce SevenZipCompressor class.

  • Add write() method for each header class.

  • Add tests for write methods.

  • Add method for registering shutil.

Changed

  • Each header classes has __slots__ definitions for speed and memory optimization.

  • Rename to ‘io’ package from ‘archiveio’

  • Each header classes has classmethod ‘retrieve’ and constructor does not reading a archive file anymore.

  • Change to internalize _read() method for each header classes.

  • get_decompressor() method now become SevenZipDecompressor class.

  • Each header classes initializes members to None in constructor.

  • Method definitions map become an internal member of SevenZipDecompressor or SevenZipCompressor class.

  • Add test package compress

Fixed

  • Fix ArchiveProperties read function.

v0.0.8

Added

  • Test for CLI.

Changed

  • Improve main function.

  • Improve tests, checks outputs with sha256

v0.0.7

Added

  • CI test on AppVeyor.

Changed

  • Worker class refactoring.

Fixed

  • Fix test cases: bugzilla_16 and github_14.

  • Test: set timezone to UTC on Unix and do nothing on Windows.

v0.0.6

Fixed

  • Fix too many file descriptors opened error.

v0.0.5

Changed

  • Test: check sha256 for extracted files

Fixed

  • Fix decompressiong archive with LZMA2 and BCJ method

  • Fix decompressing multi block archive

  • Fix file mode on unix/linux.

v0.0.4

Added

  • Set file modes for extracted files.

  • More unit test.

Changed

  • Travis-CI test on python 3.7.

Fixed

  • Fix to set extracted files timestamp as same as archived.

v0.0.3

Added

  • PyPi package index.

Fixed

  • setup: set universal = 0 because only python 3 is supported.

v0.0.2

Changed

  • refactoring all the code.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py7zr-0.9.10.tar.gz (2.6 MB view hashes)

Uploaded Source

Built Distribution

py7zr-0.9.10-py3-none-any.whl (66.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page