pylibmagic

0.5.0 · active · verified Thu Apr 16

pylibmagic is a lightweight Python package designed to simplify the installation and usage of the `libmagic` C library. It provides pre-compiled `libmagic` shared libraries via Python wheels, primarily addressing the common `ImportError: failed to find libmagic` encountered when using other `libmagic` bindings like `python-magic`. The current version is 0.5.0, with releases focusing on expanding Python version and architecture support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pylibmagic` in conjunction with the `python-magic` library. `pylibmagic` ensures that the `libmagic` C library is available for `python-magic` to use, solving common installation issues. After importing `pylibmagic`, you can then proceed to use the `magic` module from `python-magic` as intended.

import pylibmagic
import magic

# pylibmagic ensures the underlying libmagic library is available
# You can inspect the data path it uses:
print(f"pylibmagic data path: {pylibmagic.data}")

# Now, use the python-magic library as usual
try:
    m = magic.Magic()
    file_type = m.from_buffer(b"hello world")
    print(f"'hello world' is detected as: {file_type}")
    
    # Example with a common file type
    with open("temp_text.txt", "w") as f:
        f.write("This is a test file.")
    file_type_from_file = m.from_file("temp_text.txt")
    print(f"'temp_text.txt' is detected as: {file_type_from_file}")
    import os
    os.remove("temp_text.txt")
except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure 'python-magic' is also installed (`pip install python-magic`).")

view raw JSON →