Python wrapper for 7zz/7za command-line utility
Project description
๐๏ธ p7zip
Python wrapper for 7-Zip
Python interface for 7-Zip archive operations
With real-time progress tracking, encryption support, and pattern-based filtering
Installation โข Quick Start โข Features โข Examples
โจ Features
- ๐ฏ Simple API - Simple functions for archive operations
- ๐ Real-time Progress - Track compression/extraction with callbacks
- ๐ Encryption - Encryption with header protection
- ๐ฏ Smart Filtering - Include/exclude files with glob patterns
- ๐ป Cross-Platform - Works on Windows, macOS, and Linux
- ๐ง Advanced Control - Custom compression levels and methods
๐ฆ Installation
1. Install p7zip package
pip install p7zip
2. Install 7-Zip binary
p7zip requires the 7-Zip command-line tool:
๐ช Windows Installation
Option 1: 7-Zip installer for Windows and Automatic Detection (Recommended)
- Download and install 7-Zip installer for Windows from 7-zip.org/download.html
- Use auto-detection in your code:
from p7zip.binary import auto_detect_binary auto_detect_binary() # Automatically finds 7z in PATH or Program Files
- In the case that auto-detection fails, you can manually set the path:
from p7zip.binary import set_binary_path set_binary_path(r"C:\Program Files\7-Zip\7z.exe")
Option 2: 7-Zip Extra and Manual Configuration
- Download 7-Zip Extra from 7-zip.org/download.html
- Extract to a location (e.g.,
C:\Tools\) - Register in your code:
from p7zip.binary import set_binary_path set_binary_path(r"C:\Tools\7za.exe")
๐ macOS Installation
Option 1: Homebrew (Recommended)
brew install p7zip
Then use auto-detection:
from p7zip.binary import auto_detect_binary
auto_detect_binary()
Option 2: Manual
- Download from 7-zip.org
- Install and configure:
from p7zip.binary import set_binary_path set_binary_path("/usr/local/bin/7zz")
๐ง Linux Installation
Option 1: Package Manager (Recommended)
# Ubuntu/Debian
sudo apt install p7zip-full
# Fedora
sudo dnf install p7zip-full
# Arch Linux
sudo pacman -S p7zip
Then use auto-detection:
from p7zip.binary import auto_detect_binary
auto_detect_binary()
Option 2: Simple use auto_detect_binary Most Linux distros include 7za binary after installation. Just call:
from p7zip.binary import auto_detect_binary
auto_detect_binary()
Option 3: Manual Installation
- Download from 7-zip.org
- Extract and configure:
from p7zip.binary import set_binary_path set_binary_path("/usr/bin/7zz")
๐ Quick Start
1๏ธโฃ Configure the Binary
from p7zip.binary import auto_detect_binary
# Auto-detect 7-Zip in system PATH or common locations
auto_detect_binary()
Or manually set it:
from p7zip.binary import set_binary_path
set_binary_path("/usr/bin/7zz") # Linux
# set_binary_path(r"C:\Program Files\7-Zip\7z.exe") # Windows
# set_binary_path("/usr/local/bin/7zz") # macOS
2๏ธโฃ Use the Simple API
from p7zip.api import (
extract_all, compress, compress_as_7z,
list_archive_contents, verify_archive_integrity
)
# Create an archive
compress("backup.7z", ["documents/", "photos/", "config.ini"])
# Extract an archive
extract_all("backup.7z", destination="restored/")
# List contents
files = list_archive_contents("backup.7z")
print(f"Archive contains {len(files)} files")
# Verify integrity
is_valid = verify_archive_integrity("backup.7z")
if is_valid:
print("โ Archive is OK")
else:
print(f"โ Archive is corrupted")
3๏ธโฃ With Encryption & Progress
def show_progress(archivename, percentage, filename):
print(f"[{percentage:3d}%] {archivename}")
# Create encrypted archive
compress_as_7z(
"secure.7z",
["sensitive_data/"],
password="mypassword",
compression_level=9,
encrypt_headers=True,
progress_callback=show_progress
)
# Extract encrypted archive
extract_all(
"secure.7z",
destination="output/",
password="mypassword",
progress_callback=show_progress
)
4๏ธโฃ Advanced Features
from p7zip.core import SevenZipArchive
from p7zip.enums import CompressionLevel, OverwriteMode
# Full control with SevenZipArchive
with SevenZipArchive("advanced.7z", mode="w") as archive:
archive.set_password("secret123")
archive.compress(
sources=["documents/", "photos/"],
include_patterns=["*.pdf", "*.jpg", "*.png"], # Only these
exclude_patterns=["*.tmp", "*/__pycache__/*"], # Except these
compression_level=CompressionLevel.MAXIMUM,
encrypt_headers=True,
compression_method="deflate"
)
# Extract with pattern filtering
with SevenZipArchive("archive.7z", mode="r") as archive:
archive.set_password("secret123")
failed = archive.extract(
destination="output/",
include_patterns=["*.pdf"], # Only PDFs
overwrite_mode=OverwriteMode.SKIP_EXISTING
)
if failed:
print(f"CRC errors in: {failed}")
๐ API Overview
Simple API Functions
The p7zip.api module provides high-level functions for common tasks:
from p7zip.api import (
extract_all, # Extract entire archive
extract_files, # Extract specific files
extract_by_pattern, # Extract with glob patterns
compress, # Create compressed file
compress_as_7z, # Create 7z archive
compress_as_zip, # Create ZIP archive
list_archive_contents, # List all files
verify_archive_integrity, # Test archive integrity
)
Advanced Class
For complete control, use SevenZipArchive:
from p7zip.core import SevenZipArchive
from p7zip.enums import CompressionLevel, OverwriteMode, DeleteMode
# Write mode (create/compress)
with SevenZipArchive("archive.7z", mode="w") as archive:
archive.set_password("secret")
archive.compress(
sources=["file1.txt", "directory/"],
compression_level=CompressionLevel.MAXIMUM,
include_patterns=["*.py", "*.txt"],
exclude_patterns=["__pycache__/*"],
encrypt_headers=True,
delete_after_compression=DeleteMode.USE_TRASH
)
# Read mode (extract)
with SevenZipArchive("archive.7z", mode="r") as archive:
archive.set_password("secret")
failed_files = archive.extract(
destination="output/",
specific_files_or_dirs=["file1.txt"],
overwrite_mode=OverwriteMode.SKIP_EXISTING
)
Progress Callbacks
Track operations in real-time:
def progress_callback(archivename: str, percentage: int, filename: str) -> None:
"""Called during compression/extraction."""
print(f"[{percentage:3d}%] {archivename}")
def completion_callback(archivename: str, message: str) -> None:
"""Called when operation completes."""
print(f"โ {message}")
with SevenZipArchive("archive.7z", mode="w",
progress_callback=progress_callback,
completion_callback=completion_callback) as archive:
archive.compress(["data/"])
๐ฏ Compression Levels
Supports compression levels 0-9:
from p7zip.api import compress_as_7z
from p7zip.enums import CompressionLevel
# Quick backup
# CompressionLevel.FASTEST = 1
compress_as_7z("fast.7z", ["data/"], compression_level=CompressionLevel.FASTEST)
# Archive backup (small size)
# CompressionLevel.MAXIMUM = 7
compress_as_7z("compact.7z", ["data/"], compression_level=CompressionLevel.MAXIMUM)
๐ก Examples
Example 1: Selective Extraction with Progress
from p7zip.api import extract_by_pattern
def show_progress(archivename, percentage, filename):
print(f"[{percentage:3d}%] Extracting: {archivename}")
# Extract only PDF files
failed = extract_by_pattern(
"archive.7z",
destination="docs/",
include_patterns=["*.pdf", "*.txt"],
progress_callback=show_progress
)
if failed:
print(f"โ ๏ธ CRC errors: {failed}")
else:
print("โ All files extracted successfully")
Example 2: Encrypted Backup with Verification
from p7zip.api import compress_as_7z, verify_archive_integrity
def backup_with_verification(source_dir, backup_file, password):
"""Create and verify an encrypted backup."""
print("Creating backup...")
compress_as_7z(
backup_file,
[source_dir],
password=password,
compression_level=9,
encrypt_headers=True
)
print("Verifying backup...")
is_valid = verify_archive_integrity(backup_file, password)
if is_valid:
print(f"โ Backup verified: {backup_file}")
return True
else:
print(f"โ Backup corrupted.")
return False
# Create secure backup
backup_with_verification("important_data/", "backup.7z", "secure_password_123")
Example 3: Multi-Format Compression
from p7zip.api import compress_as_7z, compress_as_zip
# Create both 7z and zip versions
sources = ["documents/", "images/"]
# Maximum compression (7z)
compress_as_7z(
"archive.7z",
sources,
compression_level=9,
exclude_patterns=["*.tmp", "__pycache__/*"]
)
# Standard zip (for compatibility)
compress_as_zip(
"archive.zip",
sources,
compression_level=6,
exclude_patterns=["*.tmp", "__pycache__/*"]
)
print("โ Created archive.7z and archive.zip")
Example 4: Progress Bar Integration
from p7zip.api import extract_all
try:
from tqdm import tqdm
except ImportError:
print("Install tqdm: pip install tqdm")
exit(1)
pbar = None
def progress_callback(archivename, percentage, filename):
global pbar
if pbar is None:
pbar = tqdm(total=100, desc="Extracting", unit="%")
pbar.n = percentage
pbar.set_postfix_str(archivename[:40])
pbar.refresh()
def completion_callback(archivename, message):
global pbar
if pbar:
pbar.close()
print(f"โ {message}")
extract_all(
"large_archive.7z",
destination="output/",
progress_callback=progress_callback
)
๐จ Error Handling
from p7zip.api import extract_all
from p7zip.exceptions import (
BinaryNotFoundError,
CRCFailedError,
InvalidPasswordError,
CannotOpenArchiveError
)
try:
extract_all("backup.7z", destination="output/", password="secret")
except BinaryNotFoundError as e:
print(f"โ 7-Zip not found: {e}")
print("Install 7-Zip first!")
except InvalidPasswordError as e:
print(f"โ Wrong password: {e}")
except CannotOpenArchiveError as e:
print(f"โ Invalid archive: {e}")
except CRCFailedError as e:
print(f"โ Archive corrupted. Failed files: {e.failed_files}")
Exception Types
BinaryNotFoundError- 7-Zip binary not foundInvalidPasswordError- Wrong password for encrypted archiveCannotOpenArchiveError- Archive is invalid or corruptedCRCFailedError- CRC check failed (contains list of failed files)SevenZipExecutionError- General execution error
๐งช Testing
# Run all tests (7-Zip auto-detected automatically)
pytest tests/
# Run with coverage
pytest --cov=p7zip tests/
# Run specific test file
pytest tests/test_core.py -v
# Run integration tests only
pytest -m integration
# Run unit tests only
pytest -m unit
Note: The test suite automatically detects and configures the 7-Zip binary using auto_detect_binary().
๐ Project Structure
p7zip/
โโโ src/
โ โโโ p7zip/
โ โโโ __init__.py # Public API exports
โ โโโ api.py # High-level convenience functions
โ โโโ binary.py # Binary detection & management
โ โโโ core.py # SevenZipArchive class
โ โโโ command_executor.py # 7z command execution
โ โโโ pattern_filter.py # File pattern matching
โ โโโ filesystem_utils.py # File system utilities
โ โโโ exceptions.py # Custom exceptions
โ โโโ enums.py # Enumerations
โ โโโ types.py # Type definitions
โ โโโ py.typed # PEP 561 marker
โโโ tests/
โ โโโ conftest.py # Test configuration & fixtures
| โโโ test_binary.py # Binary detection tests
โ โโโ test_core.py # Core functionality tests
โ โโโ test_pattern_filter.py # Pattern matching tests
โ โโโ test_command_executor.py # Command execution tests
โโโ README.md
โโโ LICENSE
โโโ pyproject.toml
โ FAQ
How do I set up the 7-Zip binary?
Option 1: Auto-detection (Recommended)
from p7zip.binary import auto_detect_binary
auto_detect_binary() # Finds 7z automatically
Option 2: Manual configuration
from p7zip.binary import set_binary_path
set_binary_path("/usr/bin/7zz")
Auto-detection works great on Windows (checks Program Files), macOS (uses Homebrew), and Linux (searches PATH).
Does p7zip support multiple archive formats?
Yes! Since p7zip uses 7-Zip CLI, it supports:
- 7z - 7-Zip format (default)
- zip - ZIP format
- tar - Tar archives
- gzip - GZIP compression
- bzip2 - BZIP2 compression
- xz - XZ compression
- And many more formats supported by 7-Zip
from p7zip.api import compress_as_7z, compress_as_zip
compress_as_7z("archive.7z", ["data/"]) # 7z format
compress_as_zip("archive.zip", ["data/"]) # ZIP format
# You can also specify format in SevenZipArchive
# Simple pass extension for establishing format (7-Zip autodetect format to compress)
with SevenZipArchive("archive.tar", mode="w") as archive:
archive.compress(["data/"])
# Or use format for more control (In case you want to use a name with a different extension than the format you want to compress in, for example: archive.bin)
from p7zip.core import SevenZipArchive
with SevenZipArchive("archive.bin", mode="w") as archive:
archive.compress(["data/"], format="tar")
How accurate are progress callbacks?
Very accurate! Progress callbacks parse 7-Zip's native output in real-time, providing:
- Actual percentage completion
- Current file being processed
- Immediate updates during operation
def show_progress(archivename, percentage, filename):
print(f"[{percentage}%] {archivename}")
extract_all("archive.7z", progress_callback=show_progress)
Can I use pattern matching for selective operations?
Yes! Use include_patterns and exclude_patterns:
from p7zip.core import SevenZipArchive
with SevenZipArchive("archive.7z", mode="w") as archive:
archive.compress(
sources=["data/"],
include_patterns=["*.py", "*.txt"], # Only Python and text files
exclude_patterns=["__pycache__/*", "*.pyc"] # Skip these
)
Patterns support glob syntax:
*.ext- Match by extensiondir/*- Match in directory**/file- Match anywhere in tree
Why doesn't p7zip include 7-Zip binary?
For several reasons:
- Lightweight package - No large binary bloat
- User control - Use your preferred 7-Zip version
- License clarity - p7zip (MIT) and 7-Zip (LGPL) stay separate
- Platform flexibility - Use system-installed versions
p7zip just needs the 7z CLI tool, which is easy to install:
- Windows: Download from 7-zip.org or use installer
- macOS:
brew install p7zip - Linux:
sudo apt install p7zip-full(or equivalent)
๐ License
p7zip is licensed under the MIT License.
Third-Party Dependencies
โ ๏ธ Important: This library requires 7-Zip but does NOT distribute it.
-
send2trash - Licensed under BSD 3-Clause license
-
Website: github.com/arsenetar/send2trash
-
7-Zip - Licensed under GNU LGPL with unRAR restriction
-
Website: 7-zip.org
-
Copyright: ยฉ 1999-2024 Igor Pavlov
-
License: 7-zip.org/license.txt
Users must download and install 7-Zip separately. p7zip is merely a Python wrapper for the 7-Zip CLI tool.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file p7zip-1.0.1.tar.gz.
File metadata
- Download URL: p7zip-1.0.1.tar.gz
- Upload date:
- Size: 24.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ddd3ed59d8da9c0b349f121b156def6cf73212094ad9d4faf449bcceb877e4ab
|
|
| MD5 |
0587c1eb524fdbeb972f561914db2768
|
|
| BLAKE2b-256 |
d28b7aa69baf5a6450e342db6a4e93a79b0699b3baaac1fdb276ab1a45880a9d
|
File details
Details for the file p7zip-1.0.1-py3-none-any.whl.
File metadata
- Download URL: p7zip-1.0.1-py3-none-any.whl
- Upload date:
- Size: 28.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.8.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
35d9007ef004a06214e6869760f0b821071c10c7604d47b70bc779e240e2dc2d
|
|
| MD5 |
f91dc5e01f99d3976d35a27154766ea6
|
|
| BLAKE2b-256 |
02f7171c14ddb6882d39356c59c7183712cb731a9404d8ecdd6195046c106d37
|