Ctypes
У PHP есть модуль из которого можно «дёрнуть» любую dll/so. Следовало ожидать, что и у Python есть
Вот что получилось (finfo.py):
# -*- coding: utf8 -*-
from ctypes import *
NONE = 0 # No special handling
DEBUG = 1 # Print debugging messages to stderr
SYMLINK = 2 # If the file queried is a symlink, follow it
COMPRESS = 4 # If the file is compressed, unpack it and look at the contents
DEVICES = 8 # If the file is a block or character special device, then open the device and try to look in its content
MIME = 16 # Return a mime string, instead of a textual description
CONTINUE = 32 # Return all matches, not just the first
CHECK = 64 # Check the magic database for consistency and print warnings to stderr
PRESERVE_ATIME = 128 # On systems that support utime(2) or utimes(2), attempt to preserve the access time of files analyzed
RAW = 256 # Don’t translate unprintable characters to a ooo octal representation.
class finfo:
def __init__(self, magicfile = None, flag = NONE):
"""Инициализация. Передаются имя magic-файла (или используется размещение
по умолчанию и флаги (см. константы выше)"""
self.lib = cdll.LoadLibrary('libmagic.so.1')
# следующие функции возвращают указатель на char, что я указываю
self.lib.magic_buffer.restype = c_char_p
self.lib.magic_file.restype = c_char_p
self.lib.error.restype = c_char_p
self.magic = self.lib.magic_open(flag)
self.lib.magic_load(self.magic, magicfile)
def buffer(self, content):
"""определить содержимое из строки"""
return self.lib.magic_buffer(self.magic, content, len(content))
def file(self, filename):
"""определить содержимое файла"""
return self.lib.magic_file(self.magic, filename)
def __del__(self):
self.lib.magic_close(self.magic)Вызывается модуль просто:
import finfo
mime = finfo.finfo('/usr/share/file/magic', finfo.MIME)
print mime.file('more.png')Читайте также
Ctypes и alloc
В биндинге для Python libmapi (который я пишу, с использованием ctypes), возникла следующая задача: есть куски кода, где надо выделить память через вызовы talloc. Желательно, чтобы память сама освобождалась, когда переменная, в которой у меня указатель на эту структуру, исчезает.
2009
Комментарии 10
На версию не очень похоже.
-
lrwxrwxrwx 1 root root 22
-
для того, чтобы не заморачиваться с версиями, в библитеке есть специальный вызов, который по короткому имени (без «lib», «.so» и номера) ищет полное имя библиотеки.
А, кроме того, разве mimetypes говорит тип файла не по разрешению?