The Python module for file type identification, called ‘magic’, is not standardized

I found the hard way that the API exported by the Python module ‘magic’ differs among different versions of the module.

The version installed when installing the Debian package ‘python-magic’ expects the following API:

import magic
mymagic = magic.open(magic.MAGIC_MIME_TYPE)
mymagic.load()
mtype = mymagic.file(inpfname)
print(”The MIME type of the file %s is %s” % (inpfname,mtype))

The version installed using ‘pip install python-magic’ expects the following API:

import magic
mymagic = magic.Magic(mime=True)
mtype = mymagic.from_file(inpfname)
print(”The MIME type of the file %s is %s” % (inpfname,mtype))

The following code allows the rest of the script to work the same way with either version of ‘magic’:

import magic
def build_magic():
  try:
    mymagic = magic.open(magic.MAGIC_MIME_TYPE)
    mymagic.load()
  except AttributeError,e:
    mymagic = magic.Magic(mime=True)
    mymagic.file = mymagic.from_file
  return(mymagic)
mymagic = build_magic()
mtype = mymagic.file(inpfname)
print(”The MIME type of the file %s is %s” % (inpfname,mtype))

RSS feed | Trackback URI

Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> in your comment.