How to use python-magic 5.19-1
I need to define MIME types from files without suffix in python3 and I was thinking of python-magic as a suitable solution for this. Unfortunately this does not work as described here: https://github.com/ahupp/python-magic/blob/master/README.md
What's happening:
>>> import magic
>>> magic.from_file("testdata/test.pdf")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'from_file'
So, I looked at the object that provides me the class Magic
for which I found the documentation here:
http://filemagic.readthedocs.org/en/latest/guide.html
I was surprised that this didn't work either:
>>> with magic.Magic() as m:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'ms'
>>> m = magic.Magic()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'ms'
>>>
I couldn't find any information on how to use the class Magic
anywhere, so I kept on trial and error until I figured out what it takes for instances LP_magic_set
only ms
. Some of them are returned by modular methods
magic.magic_set()
and magic_t()
. So I tried building Magic
with any of them. When I call a method file()
from an instance, it always returns an empty result and the method errlvl()
tells me an error. 22. So how can I use magic anyway?
source to share
I think you are confusing different implementations of "python-magic"
You seem to have python-magic-5.19.1 installed , however you first link to the documentation for python-magic-0.4.6 and secondly filemagic-1.6 . I think you are better off using python-magic-0.4.6 as it is readily available in PYPI and easily installed via pip
virtual environments.
The documentation for python-magic-5.19.1 is hard to find, but I managed to get it to work like this:
>>> import magic
>>> m=magic.open(magic.MAGIC_NONE)
>>> m.load()
0
>>> m.file('/etc/passwd')
'ASCII text'
>>> m.file('/usr/share/cups/data/default.pdf')
'PDF document, version 1.5'
You can also get various magical descriptions, for example. MIME type:
>>> m=magic.open(magic.MAGIC_MIME)
>>> m.load()
0
>>> m.file('/etc/passwd')
'text/plain; charset=us-ascii'
>>> m.file('/usr/share/cups/data/default.pdf')
'application/pdf; charset=binary'
or for later versions python-magic-5.30
>>> import magic
>>> magic.detect_from_filename('/etc/passwd')
FileMagic(mime_type='text/plain', encoding='us-ascii', name='ASCII text')
>>> magic.detect_from_filename('/etc/passwd').mime_type
'text/plain'
source to share