1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| import sys import subprocess import os import json import warnings import codecs
executable = "exiftool" sentinel = b"{ready}" block_size = 4096
def _fscodec(): encoding = sys.getfilesystemencoding() errors = "strict" if encoding != "mbcs": try: codecs.lookup_error("surrogateescape") except LookupError: pass else: errors = "surrogateescape"
def fsencode(filename): if isinstance(filename, bytes): return filename else: return filename.encode(encoding, errors)
return fsencode
fsencode = _fscodec() del _fscodec
class ExifTool(object):
def __init__(self, executable_=None): if executable_ is None: self.executable = executable else: self.executable = executable_ self.running = False
def start(self): if self.running: warnings.warn("ExifTool already running; doing nothing.") return with open(os.devnull, "w") as devnull: self._process = subprocess.Popen( [self.executable, "-stay_open", "True", "-@", "-", "-common_args", "-G", "-n"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=devnull) self.running = True
def terminate(self): if not self.running: return self._process.stdin.write(b"-stay_open\nFalse\n") self._process.stdin.flush() self._process.communicate() del self._process self.running = False
def __enter__(self): self.start() return self
def __exit__(self, exc_type, exc_val, exc_tb): self.terminate()
def __del__(self): self.terminate()
def execute(self, *params): if not self.running: raise ValueError("ExifTool instance not running.") self._process.stdin.write(b"\n".join(params + (b"-execute\n",))) self._process.stdin.flush() output = b"" fd = self._process.stdout.fileno() while not output[-32:].strip().endswith(sentinel): output += os.read(fd, block_size) return output.strip()[:-len(sentinel)]
def execute_json(self, *params): params = map(fsencode, params) return json.loads(self.execute(b"-j", *params).decode("utf-8"))
def get_metadata(self, filename): return self.execute_json(filename)[0]
|