Roland's homepage

My random knot in the Web

Python bindings for libmagic

This documents how I installed Python bindings for libmagic.

There are actually different bindings for libmagic. One set is part of the original distribution. It can be found in /usr/src/contrib/file/python/. But in my opinion it is somewhat cumbersome to use and not very Pythonic.

The implementation from ahupp/python-magic in Github feels more natural.

So I cloned that.

> cd ~/tmp/src/
> git clone https://github.com/ahupp/python-magic.git
Cloning into 'python-magic'...
remote: Counting objects: 264, done.
remote: Total 264 (delta 0), reused 0 (delta 0), pack-reused 264
Receiving objects: 100% (264/264), 186.91 KiB | 0 bytes/s, done.
Resolving deltas: 100% (123/123), done.
Checking connectivity... done.
> cd python-magic/

Looking at the setup.py file, both Python2 and Python3 are supported.

Testing with Python 2.7 worked fine.

> python2.7
>>> import magic
>>> magic.from_file('README.md')
'ASCII text, with very long lines'
>>> magic.from_file('/home/rsmith/freq_enc.svg')
'SVG Scalable Vector Graphics image'
>>> magic.from_file('/home/rsmith/quotes.gz')
'gzip compressed data, was "quotes", last modified: Mon Mar  9 18:17:21 2015, from Unix'
>>> magic.from_file('/home/rsmith/meterstandenkaart_elektra.docx')
'Microsoft Word 2007+'
>>> magic.from_file('/home/rsmith/pelican-3.6.3.txz')
'XZ compressed data'

The same test was done with Python 3.4.

> python3.4
>>> import magic
>>> magic.from_file('README.md')
b'ASCII text, with very long lines'
>>> magic.from_file('/home/rsmith/freq_enc.svg')
b'SVG Scalable Vector Graphics image'
>>> magic.from_file('/home/rsmith/quotes.gz')
b'gzip compressed data, was "quotes", last modified: Mon Mar  9 18:17:21 2015, from Unix'
>>> magic.from_file('/home/rsmith/meterstandenkaart_elektra.docx')
b'Microsoft Word 2007+'
>>> magic.from_file('/home/rsmith/pelican-3.6.3.txz')
b'XZ compressed data'
>>> magic.from_file('/home/rsmith/pelican-3.6.3.txz').decode('utf8')
'XZ compressed data'

The only difference is that it returns bytes, which need to be decoded.

Seeing that the module works for boyj Python versions that I use, it is time to install them.

> su
# python2.7 setup.py install
# python2.7 setup.py clean
# python3.4 setup.py install
# python3.4 setup.py clean

←  Updating FreeBSD from source Updating Python to 3.5  →