Стих о нежносте

Да, нынче девочки не сильно образованы и не все знают, что афторы любовных стишков, такие как Бальмонт, Тургенев, Полонский, Северянин, Белый, Пастернак — давно умерли — и пишут им коменты, как живым — но зато — КАКИЕ это комменты!

Статья «Классики и девочки» с сайта «Свободная пресса» сделала мой день.

13 комментариев

Ctypes

У PHP есть модуль из которого можно «дёрнуть» любую dll/so. Следовало ожидать, что и у Python есть что-то подобное. Это что-то подобное называется ctypes. Я попробовал реализовать небольшой модуль, который обращается к библиотеке libmagic (которая занимается определением типа файла по его сигнатуре).

Вот что получилось (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')

10 комментариев