exiftool.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # -*- coding: utf-8 -*-
  2. # PyExifTool <http://github.com/smarnach/pyexiftool>
  3. # Copyright 2012 Sven Marnach
  4. # This file is part of PyExifTool.
  5. #
  6. # PyExifTool is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the licence, or
  9. # (at your option) any later version, or the BSD licence.
  10. #
  11. # PyExifTool is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  14. #
  15. # See COPYING.GPL or COPYING.BSD for more details.
  16. """
  17. PyExifTool is a Python library to communicate with an instance of Phil
  18. Harvey's excellent ExifTool_ command-line application. The library
  19. provides the class :py:class:`ExifTool` that runs the command-line
  20. tool in batch mode and features methods to send commands to that
  21. program, including methods to extract meta-information from one or
  22. more image files. Since ``exiftool`` is run in batch mode, only a
  23. single instance needs to be launched and can be reused for many
  24. queries. This is much more efficient than launching a separate
  25. process for every single query.
  26. .. _ExifTool: http://www.sno.phy.queensu.ca/~phil/exiftool/
  27. The source code can be checked out from the github repository with
  28. ::
  29. git clone git://github.com/smarnach/pyexiftool.git
  30. Alternatively, you can download a tarball_. There haven't been any
  31. releases yet.
  32. .. _tarball: https://github.com/smarnach/pyexiftool/tarball/master
  33. PyExifTool is licenced under GNU GPL version 3 or later.
  34. Example usage::
  35. import exiftool
  36. files = ["a.jpg", "b.png", "c.tif"]
  37. with exiftool.ExifTool() as et:
  38. metadata = et.get_metadata_batch(files)
  39. for d in metadata:
  40. print("{:20.20} {:20.20}".format(d["SourceFile"],
  41. d["EXIF:DateTimeOriginal"]))
  42. """
  43. from __future__ import unicode_literals
  44. import sys
  45. import subprocess
  46. import os
  47. import json
  48. import warnings
  49. import codecs
  50. try: # Py3k compatibility
  51. basestring
  52. except NameError:
  53. basestring = (bytes, str)
  54. executable = "exiftool"
  55. """The name of the executable to run.
  56. If the executable is not located in one of the paths listed in the
  57. ``PATH`` environment variable, the full path should be given here.
  58. """
  59. # Sentinel indicating the end of the output of a sequence of commands.
  60. # The standard value should be fine.
  61. sentinel = b"{ready}"
  62. # The block size when reading from exiftool. The standard value
  63. # should be fine, though other values might give better performance in
  64. # some cases.
  65. block_size = 4096
  66. # This code has been adapted from Lib/os.py in the Python source tree
  67. # (sha1 265e36e277f3)
  68. def _fscodec():
  69. encoding = sys.getfilesystemencoding()
  70. errors = "strict"
  71. if encoding != "mbcs":
  72. try:
  73. codecs.lookup_error("surrogateescape")
  74. except LookupError:
  75. pass
  76. else:
  77. errors = "surrogateescape"
  78. def fsencode(filename):
  79. """
  80. Encode filename to the filesystem encoding with 'surrogateescape' error
  81. handler, return bytes unchanged. On Windows, use 'strict' error handler if
  82. the file system encoding is 'mbcs' (which is the default encoding).
  83. """
  84. if isinstance(filename, bytes):
  85. return filename
  86. else:
  87. return filename.encode(encoding, errors)
  88. return fsencode
  89. fsencode = _fscodec()
  90. del _fscodec
  91. class ExifTool(object):
  92. """Run the `exiftool` command-line tool and communicate to it.
  93. You can pass the file name of the ``exiftool`` executable as an
  94. argument to the constructor. The default value ``exiftool`` will
  95. only work if the executable is in your ``PATH``.
  96. Most methods of this class are only available after calling
  97. :py:meth:`start()`, which will actually launch the subprocess. To
  98. avoid leaving the subprocess running, make sure to call
  99. :py:meth:`terminate()` method when finished using the instance.
  100. This method will also be implicitly called when the instance is
  101. garbage collected, but there are circumstance when this won't ever
  102. happen, so you should not rely on the implicit process
  103. termination. Subprocesses won't be automatically terminated if
  104. the parent process exits, so a leaked subprocess will stay around
  105. until manually killed.
  106. A convenient way to make sure that the subprocess is terminated is
  107. to use the :py:class:`ExifTool` instance as a context manager::
  108. with ExifTool() as et:
  109. ...
  110. .. warning:: Note that there is no error handling. Nonsensical
  111. options will be silently ignored by exiftool, so there's not
  112. much that can be done in that regard. You should avoid passing
  113. non-existent files to any of the methods, since this will lead
  114. to undefied behaviour.
  115. .. py:attribute:: running
  116. A Boolean value indicating whether this instance is currently
  117. associated with a running subprocess.
  118. """
  119. def __init__(self, executable_=None):
  120. if executable_ is None:
  121. self.executable = executable
  122. else:
  123. self.executable = executable_
  124. self.running = False
  125. def start(self):
  126. """Start an ``exiftool`` process in batch mode for this instance.
  127. This method will issue a ``UserWarning`` if the subprocess is
  128. already running. The process is started with the ``-G`` and
  129. ``-n`` as common arguments, which are automatically included
  130. in every command you run with :py:meth:`execute()`.
  131. """
  132. if self.running:
  133. warnings.warn("ExifTool already running; doing nothing.")
  134. return
  135. with open(os.devnull, "w") as devnull:
  136. self._process = subprocess.Popen(
  137. [self.executable, "-stay_open", "True", "-@", "-",
  138. "-common_args", "-G", "-n"],
  139. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  140. stderr=devnull)
  141. self.running = True
  142. def terminate(self):
  143. """Terminate the ``exiftool`` process of this instance.
  144. If the subprocess isn't running, this method will do nothing.
  145. """
  146. if not self.running:
  147. return
  148. self._process.stdin.write(b"-stay_open\nFalse\n")
  149. self._process.stdin.flush()
  150. self._process.communicate()
  151. del self._process
  152. self.running = False
  153. def __enter__(self):
  154. self.start()
  155. return self
  156. def __exit__(self, exc_type, exc_val, exc_tb):
  157. self.terminate()
  158. def __del__(self):
  159. self.terminate()
  160. def execute(self, *params):
  161. """Execute the given batch of parameters with ``exiftool``.
  162. This method accepts any number of parameters and sends them to
  163. the attached ``exiftool`` process. The process must be
  164. running, otherwise ``ValueError`` is raised. The final
  165. ``-execute`` necessary to actually run the batch is appended
  166. automatically; see the documentation of :py:meth:`start()` for
  167. the common options. The ``exiftool`` output is read up to the
  168. end-of-output sentinel and returned as a raw ``bytes`` object,
  169. excluding the sentinel.
  170. The parameters must also be raw ``bytes``, in whatever
  171. encoding exiftool accepts. For filenames, this should be the
  172. system's filesystem encoding.
  173. .. note:: This is considered a low-level method, and should
  174. rarely be needed by application developers.
  175. """
  176. if not self.running:
  177. raise ValueError("ExifTool instance not running.")
  178. self._process.stdin.write(b"\n".join(params + (b"-execute\n",)))
  179. self._process.stdin.flush()
  180. output = b""
  181. fd = self._process.stdout.fileno()
  182. while not output[-32:].strip().endswith(sentinel):
  183. output += os.read(fd, block_size)
  184. return output.strip()[:-len(sentinel)]
  185. def execute_json(self, *params):
  186. """Execute the given batch of parameters and parse the JSON output.
  187. This method is similar to :py:meth:`execute()`. It
  188. automatically adds the parameter ``-j`` to request JSON output
  189. from ``exiftool`` and parses the output. The return value is
  190. a list of dictionaries, mapping tag names to the corresponding
  191. values. All keys are Unicode strings with the tag names
  192. including the ExifTool group name in the format <group>:<tag>.
  193. The values can have multiple types. All strings occurring as
  194. values will be Unicode strings. Each dictionary contains the
  195. name of the file it corresponds to in the key ``"SourceFile"``.
  196. The parameters to this function must be either raw strings
  197. (type ``str`` in Python 2.x, type ``bytes`` in Python 3.x) or
  198. Unicode strings (type ``unicode`` in Python 2.x, type ``str``
  199. in Python 3.x). Unicode strings will be encoded using
  200. system's filesystem encoding. This behaviour means you can
  201. pass in filenames according to the convention of the
  202. respective Python version – as raw strings in Python 2.x and
  203. as Unicode strings in Python 3.x.
  204. """
  205. params = map(fsencode, params)
  206. return json.loads(self.execute(b"-j", *params).decode("utf-8"))
  207. def get_metadata_batch(self, filenames):
  208. """Return all meta-data for the given files.
  209. The return value will have the format described in the
  210. documentation of :py:meth:`execute_json()`.
  211. """
  212. return self.execute_json(*filenames)
  213. def get_metadata(self, filename):
  214. """Return meta-data for a single file.
  215. The returned dictionary has the format described in the
  216. documentation of :py:meth:`execute_json()`.
  217. """
  218. return self.execute_json(filename)[0]
  219. def get_tags_batch(self, tags, filenames):
  220. """Return only specified tags for the given files.
  221. The first argument is an iterable of tags. The tag names may
  222. include group names, as usual in the format <group>:<tag>.
  223. The second argument is an iterable of file names.
  224. The format of the return value is the same as for
  225. :py:meth:`execute_json()`.
  226. """
  227. # Explicitly ruling out strings here because passing in a
  228. # string would lead to strange and hard-to-find errors
  229. if isinstance(tags, basestring):
  230. raise TypeError("The argument 'tags' must be "
  231. "an iterable of strings")
  232. if isinstance(filenames, basestring):
  233. raise TypeError("The argument 'filenames' must be "
  234. "an iterable of strings")
  235. params = ["-" + t for t in tags]
  236. params.extend(filenames)
  237. return self.execute_json(*params)
  238. def get_tags(self, tags, filename):
  239. """Return only specified tags for a single file.
  240. The returned dictionary has the format described in the
  241. documentation of :py:meth:`execute_json()`.
  242. """
  243. return self.get_tags_batch(tags, [filename])[0]
  244. def get_tag_batch(self, tag, filenames):
  245. """Extract a single tag from the given files.
  246. The first argument is a single tag name, as usual in the
  247. format <group>:<tag>.
  248. The second argument is an iterable of file names.
  249. The return value is a list of tag values or ``None`` for
  250. non-existent tags, in the same order as ``filenames``.
  251. """
  252. data = self.get_tags_batch([tag], filenames)
  253. result = []
  254. for d in data:
  255. d.pop("SourceFile")
  256. result.append(next(iter(d.values()), None))
  257. return result
  258. def get_tag(self, tag, filename):
  259. """Extract a single tag from a single file.
  260. The return value is the value of the specified tag, or
  261. ``None`` if this tag was not found in the file.
  262. """
  263. return self.get_tag_batch(tag, [filename])[0]