I need to get mime type for some files on windows, so i've installed python-magic
(on 32-bit python 2.7.3).
It depends on unix magic
library.
Author instructs to get regex2.dll
, zlib1.dll
and magic1.dll
from gnuwin32 project.
So i saved the files to a folder and added the folder to my system PATH
.
Now when i execute magic
methods, i get missing file exception:
import magic
print(magic.Magic())
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/lex/lex.py", line 367, in <module>
test_magic()
File "C:/Users/Admin/PycharmProjects/lex/lex.py", line 364, in test_magic
print(magic.Magic())
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 52, in __init__
magic_load(self.cookie, magic_file)
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 188, in magic_load
return _magic_load(cookie, coerce_filename(filename))
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 139, in errorcheck
raise MagicException(err)
magic.MagicException: could not find any magic files!
DLLs are in the PATH, i tried debugging and magic1.dll
is located correctly, but somewhere inside library throws an exception.
Inside the gnuwin32
package i've found magic
and magic.mgc
. I placed them to the same folder, and got WindowsError: [Error 126]
on
libmagic = None
# Let's try to find magic or magic1
dll = ctypes.util.find_library('magic') or ctypes.util.find_library('magic1')
# This is necessary because find_library returns None if it doesn't find the library
if dll:
libmagic = ctypes.CDLL(dll)
This obviously happens because python tries to open magic
file as dll, which is plain text. After adding .dll
to filenames in the code i get the same magic.MagicException: could not find any magic files!
.
What files am i missing?
UPDATE:
C:\Users\Admin>file C:\123.zip -m magic
file: could not find any magic files!
C:\Users\Admin>file C:\123.zip -m "C:\@DEV\@LIB\@Magic\GetGnuWin32\bin\magic"
C:\123.zip; ASCII text, with no line terminators
C:\Users\Admin>cd C:\@DEV\@LIB\@Magic\GetGnuWin32\bin
C:\@DEV\@LIB\@Magic\GetGnuWin32\bin>file C:\123.zip -m magic
C:\123.zip; ASCII text, with no line terminators
UPDATE 2 (SOLVED):
print(magic.Magic())
magic.MagicException: could not find any magic files!
print(magic.Magic(magic_file = 'magic'))
<magic.Magic instance at 0x02A5E198>
just had to specify file explicitly
For future google visitors: Another solution is setting the %MAGIC% enviroment variable in the systems setting to point to the magic file, for me it was:
"c:\Program Files (x86)\GnuWin32\share\misc\magic"
No need to hardcode the path in your program!