
Pure Rust Python Bindings for File Type Detection
pure-magic-rs is a Python module that provides bindings to the pure-magic crate, allowing you to detect file types, MIME types, and other metadata using a pure Rust alternative to the C libmagic library. This module uses an embedded magic database, so everything works out-of-the-box with no need of a compiled database or magic rule files.
Features
- Pure Rust implementation: No C dependencies, easily cross-compilable for great compatibility
- Embedded magic database: No database file or magic rules needed
- Detect file types from buffers or files
- Retrieve MIME types, creator codes, and file extensions
- Convert results to Python dictionaries for easy integration
- Supports both "first match", "best match" and "all matches" detection strategies
Installation
pip install pure-magic-rs
Usage
Initializing the Database
from pure_magic_rs import MagicDb
db = MagicDb()
Detecting File Types from Buffers
png_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00'
result = db.first_magic_buffer(png_data, None)
print(f"Detected: {result.message} (MIME: {result.mime_type})")
result = db.best_magic_buffer(png_data)
print(f"Best match: {result.message}")
results = db.all_magics_buffer(png_data)
for r in results:
print(f"Match: {r.message}, MIME: {r.mime_type}, Strength: {r.strength}")
Detecting File Types from Files
result = db.first_magic_file("example.png")
print(f"File type: {result.message}, Extensions: {result.extensions}")
result = db.best_magic_file("example.png")
print(f"Best match: {result.message}")
results = db.all_magics_file("example.png")
for r in results:
print(f"Match: {r.message}, MIME: {r.mime_type}")
Converting Results to Dictionaries
result = db.first_magic_buffer(png_data, None)
result_dict = result.to_dict()
print(result_dict)
Handling Errors
try:
result = db.first_magic_file("nonexistent_file.txt")
except IOError as e:
print(f"Error opening file: {e}")
License
This project is dual-licensed under either: