| 105 | |
| 106 | |
| 107 | class Magic(object): |
| 108 | def __init__(self, ms): |
| 109 | self._magic_t = ms |
| 110 | |
| 111 | def close(self): |
| 112 | """ |
| 113 | Closes the magic database and deallocates any resources used. |
| 114 | """ |
| 115 | _close(self._magic_t) |
| 116 | |
| 117 | @staticmethod |
| 118 | def __tostr(s): |
| 119 | if s is None: |
| 120 | return None |
| 121 | if isinstance(s, str): |
| 122 | return s |
| 123 | try: # keep Python 2 compatibility |
| 124 | return str(s, 'utf-8') |
| 125 | except TypeError: |
| 126 | return str(s) |
| 127 | |
| 128 | @staticmethod |
| 129 | def __tobytes(b): |
| 130 | if b is None: |
| 131 | return None |
| 132 | if isinstance(b, bytes): |
| 133 | return b |
| 134 | try: # keep Python 2 compatibility |
| 135 | return bytes(b, 'utf-8') |
| 136 | except TypeError: |
| 137 | return bytes(b) |
| 138 | |
| 139 | def file(self, filename): |
| 140 | """ |
| 141 | Returns a textual description of the contents of the argument passed |
| 142 | as a filename or None if an error occurred and the MAGIC_ERROR flag |
| 143 | is set. A call to errno() will return the numeric error code. |
| 144 | """ |
| 145 | return Magic.__tostr(_file(self._magic_t, Magic.__tobytes(filename))) |
| 146 | |
| 147 | def descriptor(self, fd): |
| 148 | """ |
| 149 | Returns a textual description of the contents of the argument passed |
| 150 | as a file descriptor or None if an error occurred and the MAGIC_ERROR |
| 151 | flag is set. A call to errno() will return the numeric error code. |
| 152 | """ |
| 153 | return Magic.__tostr(_descriptor(self._magic_t, fd)) |
| 154 | |
| 155 | def buffer(self, buf): |
| 156 | """ |
| 157 | Returns a textual description of the contents of the argument passed |
| 158 | as a buffer or None if an error occurred and the MAGIC_ERROR flag |
| 159 | is set. A call to errno() will return the numeric error code. |
| 160 | """ |
| 161 | return Magic.__tostr(_buffer(self._magic_t, buf, len(buf))) |
| 162 | |
| 163 | def error(self): |
| 164 | """ |