3
votes

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.

1
Why do you think it has an open function? The source is right here: github.com/ahupp/python-magic - Blender
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

1 Answers

4
votes

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.