4

I am trying to use python-magic package, a wrapper class for libmagic.

I install using "pip install python-magic" but when I test it:

import magic
ms = magic.open(magic.MAGIC_NONE)
ms.load()

it shows that module' object has no attribute 'open'. I searched on google and somebody said that one cause is I do not have a __init__.py file. so I checked my peronsal site-packages directory. I found magic.py, magic.pyc, and a folder python_magic-0.4.3-py2.7.egg-info which just include some text files.

How can I get the __init__.py file? I checked other packages installed, some of them do have such a file.

Thanks.

user2678640
  • 71
  • 1
  • 1
  • 2
  • 2
    Why do you think it has an `open` function? The source is right here: https://github.com/ahupp/python-magic – Blender Aug 14 '13 at 08:21
  • 1
    My test code comes from another open source project using magic. I have suspected this before. By dir(magic) I only found magic_load and magic_open, so I replace the above too calls by these two, but it does not work. the return value of magic_open seems to be an int. Do you think the above code assume I am using an older version of python-magic? – user2678640 Aug 14 '13 at 08:50

1 Answers1

7

There is no magic.open() function. If you check out the python-magic documentation you can see that it has magic.from_file() and magic.from_buffer() functions.

Use magic.from_file() to test against a path name; the module opens that file for you and and determines the type. Use magic.from_buffer() to test a byte sequence (str in Python 2, bytes in Python 3).

There is also a magic.Magic() class that you can instantiate (per thread!) to alter how it operates:

Magic(mime=False, magic_file=None, mime_encoding=False)

documented as:

Create a new libmagic wrapper.

mime - if True, mimetypes are returned instead of textual descriptions
mime_encoding - if True, codec is returned
magic_file - use a mime database other than the system default

and according to the README, that is all as far as public API is concerned.

The Magic class handles magic.MAGIC_NONE internally; setting mime=True when creating a magic.Magic() instance will set a magic.MAGIC_MIME flag for example.

It looks as if the code you encountered covers a different Python magic library altogether that required more internals hand-holding. My advice: Don't try to replicate that. Use this new library and it's documented API only.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Thank you! I also found another helpful post here http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python – user2678640 Aug 15 '13 at 01:17
  • 2
    Ah, right, so there is a `python-magic` out there that is *not* listed on PyPI and uses a different API. – Martijn Pieters Aug 15 '13 at 07:35