如何使用python-magic 5.19-1
我需要从python3中没有后缀的文件中确定MIME类型,我认为python-
magic是适合的解决方案。不幸的是,它无法按此处所述运行:https : //github.com/ahupp/python-
magic/blob/master/README.md
这是怎么回事:
>>> 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'
因此,我看了一下该对象,该对象为我提供了可以在Magic
此处找到文档的类:http
:
//filemagic.readthedocs.org/en/latest/guide.html
令我惊讶的是,这也不起作用:
>>> 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'
>>>
我在任何Magic
地方都找不到有关如何使用该类的任何信息,因此我继续进行反复试验,直到我发现它只接受LP_magic_set
for的实例ms
。其中一些由模块的方法magic.magic_set()
和返回
magic_t()
。因此,我试图Magic
与他们中的任何一个实例化。然后,当我file()
从实例调用该方法时,它将始终返回空结果,并且该errlvl()
方法告诉我错误号。22.那我该如何使用魔法呢?
-
我认为您在混淆“ python-magic”的不同实现
您似乎已经安装了python-magic-5.19.1,但是,您首先参考python-
magic- 0.4.6的文档,其次参考filemagic-1.6。我认为您最好使用python-
magic-0.4.6,因为它在PYPI上很容易获得,并且很容易通过安装pip
到virtualenv环境中。python-magic-5.19.1的文档很难获得,但是我设法使它像这样工作:
>>> 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'
您还可以获得不同的魔术描述,例如MIME类型:
>>> 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'
或更新版本的
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'