summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Hupp <adam@hupp.org>2017-12-04 10:50:31 -0800
committerAdam Hupp <adam@hupp.org>2018-01-14 19:24:40 -0800
commitc49e8dbf1f77f0878de27dec65f343bfbcbcef5d (patch)
tree9c822c42ff5757fec3806c60e09ea6952c0419dd
parentbfab639ea05b3c5979cdd68d26bf8feb512ecddb (diff)
downloadpython-magic-c49e8dbf1f77f0878de27dec65f343bfbcbcef5d.tar.gz
add from_open_file to match libmagic binding featureset
-rw-r--r--magic/__init__.py11
-rwxr-xr-xtest/test.py6
2 files changed, 17 insertions, 0 deletions
diff --git a/magic/__init__.py b/magic/__init__.py
index dd86389..112ebb6 100644
--- a/magic/__init__.py
+++ b/magic/__init__.py
@@ -81,6 +81,13 @@ class Magic:
except MagicException as e:
return self._handle509Bug(e)
+ def from_open_file(self, open_file):
+ with self.lock:
+ try:
+ return maybe_decode(magic_descriptor(self.cookie, open_file.fileno()))
+ except MagicException as e:
+ return self._handle509Bug(e)
+
def from_file(self, filename):
# raise FileNotFoundException or IOError if the file does not exist
with open(filename):
@@ -254,6 +261,10 @@ _magic_buffer.errcheck = errorcheck_null
def magic_buffer(cookie, buf):
return _magic_buffer(cookie, buf, len(buf))
+magic_descriptor = libmagic.magic_descriptor
+magic_descriptor.restype = c_char_p
+magic_descriptor.argtypes = [magic_t, c_int]
+magic_descriptor.errcheck = errorcheck_null
_magic_load = libmagic.magic_load
_magic_load.restype = c_int
diff --git a/test/test.py b/test/test.py
index c6e2d9c..aa24e5f 100755
--- a/test/test.py
+++ b/test/test.py
@@ -38,6 +38,12 @@ class MagicTest(unittest.TestCase):
b = b'#!/usr/bin/env python\nprint("foo")'
self.assertEqual("text/x-python", m.from_buffer(b))
+
+ def test_open_file(self):
+ m = magic.Magic(mime=True)
+ with open(os.path.join(self.TESTDATA_DIR, "test.pdf")) as f:
+ self.assertEqual("application/pdf", m.from_open_file(f))
+
def test_mime_types(self):
dest = os.path.join(MagicTest.TESTDATA_DIR, b'\xce\xbb'.decode('utf-8'))
shutil.copyfile(os.path.join(MagicTest.TESTDATA_DIR, 'lambda'), dest)