python-magic Documentation

repository·master·Indexed 25 days ago

https://github.com/ahupp/python-magic

A Python interface to the libmagic C library for file type identification. Provides functionality to identify file types via headers using magic.from_file(), magic.from_buffer(), and the Magic class for advanced control.

Tokens
547
Snippets
1
Records
4
Agent score
34%

What's inside python-magic

  1. Install python-magic and libmagic

    master

    python-magic is a Python interface to the libmagic file type identification library. You must install both the Python package and the underlying libmagic C library.

    1. Install the Python package:
    pip install python-magic
    1. Install the libmagic C library based on your OS:
    • Debian/Ubuntu:
      sudo apt-get install libmagic1
    - **OSX (Homebrew)**:
      ```bash
    brew install libmagic
    • OSX (MacPorts):
      port install file
    - **SmartOS**:
      Install `libmagic` from source and set `LD_LIBRARY_PATH` to `<prefix>/lib`.
    
    pip install python-magic
  2. Troubleshoot common python-magic errors

    master

    'MagicException: could not find any magic files!'

    Some installations do not correctly point to the magic database file. You can specify the path explicitly in the constructor:

    magic.Magic(magic_file="path_to_magic_file")

    'WindowsError: [Error 193] %1 is not a valid Win32 application'

    This occurs when attempting to run a 32-bit libmagic DLL in a 64-bit Python build. Ensure you use 64-bit builds of libmagic for Windows.

    'WindowsError: exception: access violation writing 0x00000000'

    This may indicate a mismatch between Windows Python and Cygwin Python. Ensure your libmagic and Python builds are consistent.

    Library not found on OSX

    If python-magic fails to load the library, it may be in a non-standard location. Set the DYLD_LIBRARY_PATH environment variable to point to the library location.

  3. Identify file types using magic.from_file() and magic.from_buffer()

    master

    Use the top-level functions for simple file type identification.

    • magic.from_file(filename, mime=False): Returns a human-readable description of the file type. Set mime=True to return the MIME type.
    • magic.from_buffer(buffer, mime=False): Returns the file type from a byte buffer.

    Note: It is recommended to use at least the first 2048 bytes of a buffer to avoid incorrect identification.

  4. Use the Magic class for advanced control

    master

    The Magic class provides more direct control, such as overriding the magic database file or enabling decompression.

    Warning: The Magic class is not thread-safe. Attempting to share a Magic instance across multiple threads will cause it to throw an error. It is not recommended for general use unless specific control is required.