Repository: sylikc/pyexiftool
Branch: master
Commit: e54f96cd7575
Files: 62
Total size: 271.1 KB
Directory structure:
gitextract_fe9h4enf/
├── .github/
│ └── workflows/
│ └── lint-and-test.yml
├── .gitignore
├── CHANGELOG.md
├── COMPATIBILITY.txt
├── COPYING.BSD
├── COPYING.GPL
├── LICENSE
├── MANIFEST.in
├── README.rst
├── docs/
│ ├── .gitignore
│ ├── Makefile
│ ├── make.bat
│ └── source/
│ ├── conf.py
│ ├── examples.rst
│ ├── faq.rst
│ ├── index.rst
│ ├── installation.rst
│ ├── intro.rst
│ ├── maintenance/
│ │ └── release-process.rst
│ ├── package.rst
│ └── reference/
│ ├── 1-exiftool.rst
│ ├── 2-helper.rst
│ └── 3-alpha.rst
├── exiftool/
│ ├── __init__.py
│ ├── constants.py
│ ├── exceptions.py
│ ├── exiftool.py
│ ├── experimental.py
│ └── helper.py
├── mypy.ini
├── scripts/
│ ├── README.txt
│ ├── flake8.bat
│ ├── flake8.ini
│ ├── flake8_requirements.txt
│ ├── mypy.bat
│ ├── mypy_reqiuirements.txt
│ ├── pytest.bat
│ ├── pytest_requirements.txt
│ ├── sphinx_docs.bat
│ ├── unittest.bat
│ └── windows.coveragerc
├── setup.cfg
├── setup.py
└── tests/
├── README.txt
├── __init__.py
├── common_util.py
├── files/
│ ├── README.txt
│ └── my_makernotes.config
├── test_alpha.py
├── test_exiftool_attr.py
├── test_exiftool_bytes.py
├── test_exiftool_configfile.py
├── test_exiftool_logger.py
├── test_exiftool_misc.py
├── test_exiftool_process.py
├── test_helper_checkexecute.py
├── test_helper_checktagnames.py
├── test_helper_gettags.py
├── test_helper_misc.py
├── test_helper_run.py
├── test_helper_settags.py
└── test_helper_tags_float.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/lint-and-test.yml
================================================
name: Lint and Test
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
python-version: [3.6, 3.7, 3.8, 3.9, '3.10', 3.11, 3.12]
env:
exiftool_version: 12.15
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
# while https://github.com/actions/setup-python recommends using a specific dependency version to use cache
# we'll see if this just uses it in default configuration
# this can't be enabled unless a requirements.txt file exists. PyExifTool doesn't have any hard requirements
#cache: 'pip'
- name: Cache Perl ExifTool Download
# https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows
uses: actions/cache@v2
env:
cache-name: cache-perl-exiftool
with:
# path where we would extract the ExifTool source files
path: Image-ExifTool-${{ env.exiftool_version }}
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.exiftool_version }}
- name: Install dependencies
run: |
# don't have to do this on the GitHub runner, it's going to always be the latest
#python -m pip install --upgrade pip
# the setup-python uses it this way instead of calling it via module, so maybe this will cache ...
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
# latest version not yet available on Ubuntu Focal 20.04 LTS, but it's better to install it with all dependencies first
sudo apt-get install -qq libimage-exiftool-perl
# print this in the log
exiftool -ver
# get just the minimum version to build and compile, later we can go with latest version to test
# working with cache: only get if the directory doesn't exist
if [ ! -d Image-ExifTool-${{ env.exiftool_version }} ]; then wget http://backpan.perl.org/authors/id/E/EX/EXIFTOOL/Image-ExifTool-${{ env.exiftool_version }}.tar.gz; fi
# extract if it was downloaded
if [ -f Image-ExifTool-${{ env.exiftool_version }}.tar.gz ]; then tar xf Image-ExifTool-${{ env.exiftool_version }}.tar.gz; fi
cd Image-ExifTool-${{ env.exiftool_version }}/
# https://exiftool.org/install.html#Unix
perl Makefile.PL
make test
export PATH=`pwd`:$PATH
cd ..
exiftool -ver
# save this environment for subsequent steps
# https://brandur.org/fragments/github-actions-env-vars-in-env-vars
echo "PATH=`pwd`:$PATH" >> $GITHUB_ENV
- name: Install pyexiftool
run: |
# install all supported json processors for tests
python -m pip install .[json,test]
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
================================================
FILE: .gitignore
================================================
*.pyc
__pycache__/
build/
dist/
MANIFEST
*.egg-info/
# pytest-cov db
.coverage
# tests will be made to write to temp directories with this prefix
tests/exiftool-tmp-*
# IntelliJ
.idea
================================================
FILE: CHANGELOG.md
================================================
# PyExifTool Changelog
Date (Timezone) | Version | Comment
---------------------------- | ------- | -------
03/13/2021 01:54:44 PM (PST) | 0.5.0a0 | no functional code changes ... yet. this is currently on a separate branch referring to [Break down Exiftool into 2+ classes, a raw Exiftool, and helper classes](https://github.com/sylikc/pyexiftool/discussions/10) and [Deprecating Python 2.x compatibility](https://github.com/sylikc/pyexiftool/discussions/9) . In time this refactor will be the future of PyExifTool, once it stabilizes. I'll make code-breaking updates in this branch from build to build and take comments to make improvements. Consider the 0.5.0 "nightly" quality. Also, changelog versions were modified because I noticed that the LAST release from smarnach is tagged with v0.2.0
02/28/2022 12:39:57 PM (PST) | 0.5.0 | complete refactor of the PyExifTool code. Lots of changes. Some code breaking changes. Not directly backwards-compatible with v0.4.x. See COMPATIBILITY.TXT to understand all the code-breaking changes.
03/02/2022 07:07:26 AM (PST) | 0.5.1 | v0.5 Sphinx documentation generation finally working. Lots of reStructuredText written to make the documentation better! There's no functional changes to PyExifTool, but after several days and hours of effort, every single docstring in ExifTool and ExifToolHelper was updated to reflect all v0.5.0 changes. ExifToolAlpha was largely untouched because the methods exposed haven't really been updated this time.
03/03/2022 06:49:31 PM (PST) | 0.5.2 | Predicting the next most requested method: ExifToolHelper now has a set_tags() method similar to the get_tags() method. This was pulled from ExifToolAlpha, combining the old set_tags/set_tags_batch into one method. Added a new constructor/property to ExifToolHelper: check_execute, which (by default) will raise ExifToolExecuteError when the exit status code from exiftool subprocess is non-zero. This should help users debug otherwise silent errors. Also updated more docstrings and added maintenance script to generate docs.
03/26/2022 06:48:01 AM (PDT) | 0.5.3 | Quite a few docstring changes ExifToolHelper's get_tags() and set_tags() checks tag names to prevent inadvertent write behavior Renamed a few of the errors to make sure the errors are explicit ExifToolHelper() has some static helper methods which can be used when extending the class (ExifToolAlpha.set_keywords_batch() demonstrates a sample usage). setup.py tweaked to make it Beta rather than Alpha ExifToolAlpha.get_tag() updated to make it more robust. Fixed ujson compatibility Cleaned up and refactored testing.
08/27/2022 06:06:32 PM (PDT) | 0.5.4 | New Feature: added raw_bytes parameter to ExifTool.execute() to return bytes only with no decoding conversion. Changed: ExifTool.execute() now accepts both [str,bytes]. When given str, it will encode according to the ExifTool.encoding property. Changed: ExifToolHelper.execute() now accepts Any type, and will do a str() on any non-str parameter. Technical change: Popen() no longer uses an -encoding parameter, therefore working with the socket is back to bytes when interfacing with the exiftool subprocess. This should be invisible to most users as the default behavior will still be the same. Tests: Created associated test with a custom makernotes example to write and read back bytes. Docs: Updated documentation with comprehensive samples, and a better FAQ section for common problems.
12/30/2022 02:35:18 PM (PST) | 0.5.5 | No functional changes, only a huge speed improvement with large operations :: Update: Speed up large responses from exiftool. Instead of using + string concatenation, uses list appends and reverse(), which results in a speedup of 10x+ for large operations. See more details from the [reported issue](https://github.com/sylikc/pyexiftool/issues/60) and [PR 61](https://github.com/sylikc/pyexiftool/pull/61) by [prutschman](https://github.com/prutschman)
10/22/2023 03:21:46 PM (PDT) | 0.5.6 | New Feature: added method ExifTool.set_json_loads() which allows setting a method to replace the json.loads() called in ExifTool.execute_json(). Changed: ujson is no longer used by default when available. Use the set_json_loads() to enable manually This permits passing additional configuration parameters to address the [reported issue](https://github.com/sylikc/pyexiftool/issues/76). All documentation has been updated and two accompanying FAQ entries have been written to describe the new functionality. Test cases have been written to test the new functionality and some baseline exiftool tests to ensure that the behavior remains consistent across tests.
Follow maintenance/release-process.html when releasing a version.
# PyExifTool Changelog Archive (v0.2 - v0.4)
Date (Timezone) | Version | Comment
---------------------------- | ------- | -------
07/17/2019 12:26:16 AM (PDT) | 0.2.0 | Source was pulled directly from https://github.com/smarnach/pyexiftool with a complete bare clone to preserve all history. Because it's no longer being updated, I will pull all merge requests in and make updates accordingly
07/17/2019 12:50:20 AM (PDT) | 0.2.1 | Convert leading spaces to tabs. (I'm aware of [PEP 8](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) recommending spaces over tabs, but I <3 tabs)
07/17/2019 12:52:33 AM (PDT) | 0.2.2 | Merge [Pull request #10 "add copy_tags method"](https://github.com/smarnach/pyexiftool/pull/10) by [Maik Riechert (letmaik) Cambridge, UK](https://github.com/letmaik) on May 28, 2014 *This adds a small convenience method to copy any tags from one file to another. I use it for several month now and it works fine for me.*
07/17/2019 01:05:37 AM (PDT) | 0.2.3 | Merge [Pull request #25 "Added option for keeping print conversion active. #25"](https://github.com/smarnach/pyexiftool/pull/25) by [Bernhard Bliem (bbliem)](https://github.com/bbliem) on Jan 17, 2019 *For some tags, disabling print conversion (as was the default before) would not make much sense. For example, if print conversion is deactivated, the value of the Composite:LensID tag could be reported as something like "8D 44 5C 8E 34 3C 8F 0E". It is doubtful whether this is useful here, as we would then need to look up what this means in a table supplied with exiftool. We would probably like the human-readable value, which is in this case "AF-S DX Zoom-Nikkor 18-70mm f/3.5-4.5G IF-ED".* *Disabling print conversion makes sense for a lot of tags (e.g., it's nicer to get as the exposure time not the string "1/2" but the number 0.5). In such cases, even if we enable print conversion, we can disable it for individual tags by appending a # symbol to the tag name.*
07/17/2019 01:20:15 AM (PDT) | 0.2.4 | Merge with slight modifications to variable names for clarity (sylikc) [Pull request #27 "Add "shell" keyword argument to ExifTool initialization"](https://github.com/smarnach/pyexiftool/pull/27) by [Douglas Lassance (douglaslassance) Los Angeles, CA](https://github.com/douglaslassance) on 5/29/2019 *On Windows this will allow to run exiftool without showing the DOS shell.* **This might break Linux but I don't know for sure** Alternative source location with only this patch: https://github.com/blurstudio/pyexiftool/tree/shell-option
07/17/2019 01:24:32 AM (PDT) | 0.2.5 | Merge [Pull request #19 "Correct dependency for building an RPM."](https://github.com/smarnach/pyexiftool/pull/19) by [Achim Herwig (Achimh3011) Munich, Germany](https://github.com/Achimh3011) on Aug 25, 2016 **I'm not sure if this is entirely necessary, but merging it anyways**
07/17/2019 02:09:40 AM (PDT) | 0.2.6 | Merge [Pull request #15 "handling Errno:11 Resource temporarily unavailable"](https://github.com/smarnach/pyexiftool/pull/15) by [shoyebi](https://github.com/shoyebi) on Jun 12, 2015
07/18/2019 03:40:39 AM (PDT) | 0.2.7 | set_tags and UTF-8 cmdline - Merge in the first set of changes by Leo Broska related to [Pull request #5 "add set_tags_batch, set_tags + constructor takes added options"](https://github.com/smarnach/pyexiftool/pull/5) by [halloleo](https://github.com/halloleo) on Aug 1, 2012 but this is sourced from [jmathai/elodie's 6114328 Jun 22,2016 commit](https://github.com/jmathai/elodie/blob/6114328f325660287d1998338a6d5e6ba4ccf069/elodie/external/pyexiftool.py)
07/18/2019 03:59:02 AM (PDT) | 0.2.8 | Merge another commit fromt he jmathai/elodie [zserg on Mar 12, 2016](https://github.com/jmathai/elodie/blob/af36de091e1746b490bed0adb839adccd4f6d2ef/elodie/external/pyexiftool.py) seems to do UTF-8 encoding on set_tags
07/18/2019 04:01:18 AM (PDT) | 0.2.9 | minor change it looks like a rename to match PEP8 coding standards by [zserg on Aug 21, 2016](https://github.com/jmathai/elodie/blob/ad1cbefb15077844a6f64dca567ea5600477dd52/elodie/external/pyexiftool.py)
07/18/2019 04:05:36 AM (PDT) | 0.2.10 | [Fallback to latin if utf-8 decode fails in pyexiftool.py](https://github.com/jmathai/elodie/commit/fe70227c7170e01c8377de7f9770e761eab52036#diff-f9cf0f3eed27e85c9c9469d0e0d431d5) by [jmathai](https://github.com/jmathai/elodie/commits?author=jmathai) on Sep 7, 2016
07/18/2019 04:14:32 AM (PDT) | 0.2.11 | Merge the test cases from the [Pull request #5 "add set_tags_batch, set_tags + constructor takes added options"](https://github.com/smarnach/pyexiftool/pull/5) by [halloleo](https://github.com/halloleo) on Aug 1, 2012
07/18/2019 04:34:46 AM (PDT) | 0.3.0 | changed the setup.py licensing and updated the version numbering as in changelog changed the version number scheme, as it appears the "official last release" was 0.2.0 tagged. There's going to be a lot of things broken in this current build, and I'll fix it as they come up. I'm going to start playing with the library and the included tests and such. There's one more pull request #11 which would be pending, but it duplicates the extra arguments option. I'm also likely to remove the print conversion as it's now covered by the extra args. I'll also rename some variable names with the addedargs patch **for my changes (sylikc), I can only guarantee they will work on Python 3.7, because that's my environment... and while I'll try to maintain compatibility, there's no guarantees**
07/18/2019 05:06:19 AM (PDT) | 0.3.1 | make some minor tweaks to the naming of the extra args variable. The other pull request 11 names them params, and when I decide how to merge that pull request, I'll probably change the variable names again.
07/19/2019 12:01:22 AM (PDT) | 0.3.2 | fix the select() problem for windows, and fix all tests
07/19/2019 12:54:39 AM (PDT) | 0.3.3 | Merge a piece of [Pull request #11 "Robustness enhancements](https://github.com/smarnach/pyexiftool/pull/11) by [Matthias Kiefer (kiefermat)](https://github.com/kiefermat) on Oct 27, 2014 *On linux call prctl in subprocess to be sure that the exiftool child process is killed even if the parent process is killed by itself* also removed print_conversion also merged the common_args and added_args into one args list
07/19/2019 01:18:26 AM (PDT) | 0.3.4 | Merge the rest of Pull request #11. Added the other pieces, however, I added them as "wrappers" instead of modifying the interface of the original code. I feel like the additions here are overly done, and as I understand the code more, I'll either remove it or incorporate it into single functions from #11 *When getting json results, verify that the results returned by exiftool actually belong to the correct file by checking the SourceFile property of the returned result* and also *Added possibility to provide different exiftools params for each file separately*
07/19/2019 01:22:48 AM (PDT) | 0.3.5 | changed a bit of the test_exiftool so all the tests pass again
01/04/2020 11:59:14 AM (PST) | 0.3.6 | made the tests work with the latest output of ExifTool. This is the final version which is named "exiftool"
01/04/2020 12:16:51 PM (PST) | 0.4.0 | pyexiftool rename (and make all tests work again) ... I also think that the pyexiftool.py has gotten too big. I'll probably break it out into a directory structure later to make it more maintainable
02/01/2020 05:09:43 PM (PST) | 0.4.1 | incorporated pull request #2 and #3 by ickc which added a "no_output" feature and an import for ujson if it's installed. Thanks for the updates!
04/09/2020 04:25:31 AM (PDT) | 0.4.2 | roll back 0.4.0's pyexiftool rename. It appears there's no specific PEP to have to to name PyPI projects to be py. The only convention I found was https://www.python.org/dev/peps/pep-0423/#use-standard-pattern-for-community-contributions which I might look at in more detail
04/09/2020 05:15:40 AM (PDT) | 0.4.3 | initial work of moving the exiftool.py into a directory preparing to break it down into separate files to make the codebase more manageable
03/12/2021 01:37:30 PM (PST) | 0.4.4 | no functional code changes. Revamped the setup.py and related files to release to PyPI. Added all necessary and recommended files into release
03/12/2021 02:03:38 PM (PST) | 0.4.5 | no functional code changes. re-release with new version because I accidentally included the "test" package with the PyPI 0.4.4 release. I deleted it instead of yanking or doing a post release this time... just bumped the version. "test" folder renamed to "tests" as per convention, so the build will automatically ignore it
04/08/2021 03:38:46 PM (PDT) | 0.4.6 | added support for config files in constructor -- Merged pull request #7 from @asielen and fixed a bug referenced in the discussion https://github.com/sylikc/pyexiftool/pull/7
04/19/2021 02:37:02 PM (PDT) | 0.4.7 | added support for writing a list of values in set_tags_batch() which allows setting individual keywords (and other tags which are exiftool lists) -- contribution from @davidorme referenced in issue https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234
04/28/2021 01:50:59 PM (PDT) | 0.4.8 | no functional changes, only a minor documentation link update -- Merged pull request #16 from @beng
05/19/2021 09:37:52 PM (PDT) | 0.4.9 | test_tags() parameter encoding bugfix and a new test case TestTagCopying -- Merged pull request #19 from @jangop I also added further updates to README.rst to point to my repo and GH pages I fixed the "previous versions" naming to match the v0.2.0 start. None of them were published, so I changed the version information here just to make it less confusing to a casual observer who might ask "why did you have 0.1 when you forked off on 0.2.0?" Sven Marnach's releases were all 0.1, but he tagged his last release v0.2.0, which is my starting point
08/22/2021 08:32:30 PM (PDT) | 0.4.10 | logger changed to use logging.getLogger(__name__) instead of the root logger -- Merged pull request #24 from @nyoungstudios
08/22/2021 08:34:45 PM (PDT) | 0.4.11 | no functional code changes. Changed setup.py with updated version and Documentation link pointed to sylikc.github.io -- as per issue #27 by @derMart
08/22/2021 09:02:33 PM (PDT) | 0.4.12 | fixed a bug ExifTool.terminate() where there was a typo. Kept the unused outs, errs though. -- from suggestion in pull request #26 by @aaronkollasch
02/13/2022 03:38:45 PM (PST) | 0.4.13 | (NOTE: Barring any critical bug, this is expected to be the LAST Python 2 supported release!) added GitHub actions. fixed bug in execute_json_wrapper() 'error' was not defined syntactically properly -- merged pull request #30 by https://github.com/jangop
# Changes around the web
Check for changes at the following resources to see if anyone has added some nifty features. While we have the most active fork, I'm just one of the many forks, spoons, and knives!
We can also direct users here or answer existing questions as to how to use the original version of ExifTool.
(last checked 10/23/2023 all)
search "pyexiftool github" to see if you find any more random ports/forks
check for updates https://github.com/smarnach/pyexiftool/pulls
check for new open issues https://github.com/smarnach/pyexiftool/issues?q=is%3Aissue+is%3Aopen
answer relevant issues on stackoverflow (make sure it's related to the latest version) https://stackoverflow.com/search?tab=newest&q=pyexiftool&searchOn=3
================================================
FILE: COMPATIBILITY.txt
================================================
PyExifTool does not guarantee source-level compatibility from one release to the next.
That said, efforts will be made to provide well-documented API-level compatibility,
and if there are major API changes, migration documentation will be provided, when
possible.
----
v0.1.x - v0.2.0 = smarnach code, API compatible
v0.2.1 - v0.4.13 = original v0.2 code with all PRs, a superset of functionality on Exiftool class
v0.5.0 - = not API compatible with the v0.4.x series. Broke down functionality stability by classes. See comments below:
----
API changes between v0.4.x and v0.5.0:
PYTHON CHANGE: Old: Python 2.6 supported. New: Python 3.6+ required
CHANGED: Exiftool constructor:
RENAME: "executable_" parameter to "executable"
DEFAULT BEHAVIOR: "common_args" defaults to ["-G", "-n"] instead of None. Old behavior set -G and -n if "common_args" is None. New behavior "common_args" = [] if common_args is None.
DEFAULT: Old: "win_shell" defaults to True. New: "win_shell" defaults to False.
NEW: "encoding" parameter
NEW: "logger" parameter
NEW PROPERTY GET/SET: a lot of properties were added to do get/set validation, and parameters can be changed outside of the constructor.
METHOD RENAME: starting the process was renamed from "start" to "run"
MINIMUM TOOL VERSION: exiftool command line utility minimum requirements. Old: 8.60. New: 12.15
ENCODING CHANGE: execute() and execute_json() no longer take bytes, but is guided by the encoding set in constructor/property
ERROR CHANGE: execute_json() when no json was not returned (such as a set metadata operation) => Old: raised an error. New: returns custom ExifToolException
FEATURE REMOVAL: execute_json() no longer detects the '-w' flag being passed used in common_args.
If a user uses this flag, expect no output.
(detection in common_args was clunky anyways because -w can be passed as a per-run param for the same effect)
all methods other than execute() and execute_json() moved to ExifToolHelper or ExifToolAlpha class.
ExifToolHelper adds methods:
get_metadata()
get_tags()
NEW CONVENTION: all methods take "files" first, "tags" second (if needed) and "params" last
ExifToolAlpha adds all remaining methods in an alpha-quality way
NOTE: ExifToolAlpha has not been updated yet to use the new convention, and the edge case code may be removed/changed at any time.
If you depend on functionality provided by ExifToolAlpha, please submit an Issue to start a discussion on cleaning up the code and moving it into ExifToolHelper
----
================================================
FILE: COPYING.BSD
================================================
Copyright 2012 Sven Marnach, 2019-2023 Kevin M (sylikc)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SVEN MARNACH BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: COPYING.GPL
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: LICENSE
================================================
PyExifTool
Copyright 2019-2023 Kevin M (sylikc)
Copyright 2012-2014 Sven Marnach
PyExifTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the licence, or
(at your option) any later version, or the BSD licence.
PyExifTool is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See COPYING.GPL or COPYING.BSD for more details.
================================================
FILE: MANIFEST.in
================================================
include README.rst COPYING doc/Makefile doc/conf.py doc/*.rst
================================================
FILE: README.rst
================================================
**********
PyExifTool
**********
.. image:: https://img.shields.io/badge/Docs-latest-blueviolet
:alt: GitHub Pages
:target: http://sylikc.github.io/pyexiftool/
.. HIDE_FROM_PYPI_START
.. image:: https://github.com/sylikc/pyexiftool/actions/workflows/lint-and-test.yml/badge.svg
:alt: GitHub Actions
:target: https://github.com/sylikc/pyexiftool/actions
.. image:: https://img.shields.io/pypi/v/pyexiftool.svg
:target: https://pypi.org/project/PyExifTool/
:alt: PyPI Version
.. HIDE_FROM_PYPI_END
.. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg
:target: https://pypi.org/project/PyExifTool/
:alt: Supported Python Versions
.. image:: https://pepy.tech/badge/pyexiftool
:target: https://pepy.tech/project/pyexiftool
:alt: Total PyPI Downloads
.. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d
:target: https://pepy.tech/project/pyexiftool
:alt: PyPI Downloads this month
.. DESCRIPTION_START
.. BLURB_START
PyExifTool is a Python library to communicate with an instance of
`Phil Harvey's ExifTool`_ command-line application.
.. _Phil Harvey's ExifTool: https://exiftool.org/
.. BLURB_END
The library provides the class ``exiftool.ExifTool`` that runs the command-line
tool in batch mode and features methods to send commands to that
program, including methods to extract meta-information from one or
more image files. Since ``exiftool`` is run in batch mode, only a
single instance needs to be launched and can be reused for many
queries. This is much more efficient than launching a separate
process for every single query.
.. DESCRIPTION_END
.. contents::
:depth: 2
:backlinks: none
Example Usage
=============
Simple example: ::
import exiftool
files = ["a.jpg", "b.png", "c.tif"]
with exiftool.ExifToolHelper() as et:
metadata = et.get_metadata(files)
for d in metadata:
print("{:20.20} {:20.20}".format(d["SourceFile"],
d["EXIF:DateTimeOriginal"]))
Refer to documentation for more `Examples and Quick Start Guide`_
.. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html
.. INSTALLATION_START
Getting PyExifTool
==================
PyPI
------------
Easiest: Install a version from the official `PyExifTool PyPI`_
::
python -m pip install -U pyexiftool
.. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/
From Source
------------
#. Check out the source code from the github repository
* ``git clone git://github.com/sylikc/pyexiftool.git``
* Alternatively, you can download a tarball_.
#. Run setup.py to install the module from source
* ``python setup.py install [--user|--prefix=]``
.. _tarball: https://github.com/sylikc/pyexiftool/tarball/master
PyExifTool Dependencies
=======================
Python
------
PyExifTool runs on **Python 3.6+**. (If you need Python 2.6 support,
please use version v0.4.x). PyExifTool has been tested on Windows and
Linux, and probably also runs on other Unix-like platforms.
Phil Harvey's exiftool
----------------------
For PyExifTool to function, ``exiftool`` command-line tool must exist on
the system. If ``exiftool`` is not on the ``PATH``, you can specify the full
pathname to it by using ``ExifTool(executable=)``.
PyExifTool requires a **minimum version of 12.15** (which was the first
production version of exiftool featuring the options to allow exit status
checks used in conjuction with ``-echo3`` and ``-echo4`` parameters).
To check your ``exiftool`` version:
::
exiftool -ver
Windows/Mac
^^^^^^^^^^^
Windows/Mac users can download the latest version of exiftool:
::
https://exiftool.org
Linux
^^^^^
Most current Linux distributions have a package which will install ``exiftool``.
Unfortunately, some do not have the minimum required version, in which case you
will have to `build from source`_.
* Ubuntu
::
sudo apt install libimage-exiftool-perl
* CentOS/RHEL
::
yum install perl-Image-ExifTool
.. _build from source: https://exiftool.org/install.html#Unix
.. INSTALLATION_END
Documentation
=============
The current documentation is available at `sylikc.github.io`_.
::
http://sylikc.github.io/pyexiftool/
.. _sylikc.github.io: http://sylikc.github.io/pyexiftool/
Package Structure
-----------------
.. DESIGN_INFO_START
PyExifTool was designed with flexibility and extensibility in mind. The library consists of a few classes, each with increasingly more features.
The base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality.
.. DESIGN_INFO_END
.. DESIGN_CLASS_START
* ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process.
It contains only the core features with no extra fluff.
The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process.
* The API is considered stable and should not change much with future releases.
* ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality. It overloads
some inherited functions to turn common errors into warnings and adds logic to make
``exiftool.ExifTool`` easier to use.
For example, ``ExifToolHelper`` provides wrapper functions to get metadata, and auto-starts the exiftool instance if it's not running (instead of raising an Exception).
``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``.
* More methods may be added and/or slight API tweaks may occur with future releases.
* ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods.
These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design.
``ExifToolAlpha`` is *not* up to the rigorous testing standard of both
``ExifTool`` or ``ExifToolHelper``. There may be old, buggy, or defunct code.
* This is the least polished of the classes and functionality/API may be changed/added/removed on any release.
* **NOTE: The methods exposed may be changed/removed at any time.**
* If you are using any of these methods in your project, please `Submit an Issue`_ to start a discussion on making those functions more robust, and making their way into ``ExifToolHelper``.
(Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.)
.. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues
.. DESIGN_CLASS_END
Brief History
=============
.. HISTORY_START
PyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a
stackoverflow question `Call exiftool from a python script?`_. Over time,
Sven refined the code, added tests, documentation, and a slew of improvements.
While PyExifTool gained popularity, Sven `never intended to maintain it`_ as
an active project. The `original repository`_ was last updated in 2014.
Over the years, numerous issues were filed and several PRs were opened on the
stagnant repository. In early 2019, `Martin Čarnogurský`_ created a
`PyPI release`_ from the 2014 code with some minor updates. Coincidentally in
mid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging
the PR and issues which were reported on Sven's issues/PR page.
In late 2019 and early 2020 there was a discussion started to
`Provide visibility for an active fork`_. There was a conversation to
transfer ownership of the original repository, have a coordinated plan to
communicate to PyExifTool users, amongst other things, but it never materialized.
Kevin M (sylikc) made the first release to the PyPI repository in early 2021.
At the same time, discussions were started, revolving around
`Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_.
The latest version is the result of all of those discussions, designs,
and development. Special thanks to the community contributions, especially
`Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_.
.. _Sven Marnach: https://github.com/smarnach/pyexiftool
.. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210
.. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073
.. _original repository: https://github.com/smarnach/pyexiftool
.. _Martin Čarnogurský: https://github.com/RootLUG
.. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history
.. _Kevin M (sylikc): https://github.com/sylikc
.. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31
.. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9
.. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10
.. _Jan Philip Göpfert: https://github.com/jangop
.. _Seth P: https://github.com/csparker247
.. _Kolen Cheung: https://github.com/ickc
.. HISTORY_END
Licence
=======
.. LICENSE_START
PyExifTool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the licence, or
(at your option) any later version, or the BSD licence.
PyExifTool is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See ``LICENSE`` for more details.
.. LICENSE_END
================================================
FILE: docs/.gitignore
================================================
_build/
================================================
FILE: docs/Makefile
================================================
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
SOURCEDIR = source
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyExifTool.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyExifTool.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/PyExifTool"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyExifTool"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
================================================
FILE: docs/make.bat
================================================
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
================================================
FILE: docs/source/conf.py
================================================
# -*- coding: utf-8 -*-
#
# PyExifTool documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 12 17:42:54 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
from pathlib import Path
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent
# "Path.parent is a purely lexical operation
# If you want to walk an arbitrary filesystem path upwards,
# it is recommended to first call Path.resolve() so as to
# resolve symlinks and eliminate .. components."
sys.path.insert(1, Path(__file__).resolve().parent.parent)
# -- Project information -----------------------------------------------------
# General information about the project.
project = 'PyExifTool'
copyright = '2023, Kevin M (sylikc)'
author = 'Kevin M (sylikc)'
# read directly from exiftool's version instead of hard coding it here
import exiftool
from packaging import version as pv
et_ver = pv.parse(exiftool.__version__)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = f'{et_ver.major}.{et_ver.minor}'
# The full version, including alpha/beta/rc tags.
release = exiftool.__version__
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc', # Core library for html generation from docstrings
'sphinx.ext.autodoc.typehints',
#'sphinx.ext.autosummary', # Create neat summary tables
'autoapi.extension', # pip install sphinx-autoapi
'sphinx_autodoc_typehints', # pip install sphinx-autodoc-typehints
'sphinx.ext.inheritance_diagram',
]
#autosummary_generate = True # Turn on sphinx.ext.autosummary
autoapi_type = 'python'
autoapi_dirs = ['../../exiftool']
autoapi_member_order = 'groupwise'
#autoapi_python_use_implicit_namespaces = True
# make my life easier, configure the autoapi with specific options for things that I care about ... aka
# hide 'private-members' - inheriting classes should not have to handle or interfere with private variables
# hide 'imported-members' - after all i import the submodules into the base namespace - don't need it to show twice
autoapi_options = [ 'members', 'undoc-members', 'show-inheritance', 'show-inheritance-diagram', 'show-module-summary', 'special-members', ]
#autoapi_generate_api_docs = False
autoapi_python_class_content = 'both' # show __init__ with class docstring
# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_typehints
# comment out when all documentation has documented parameters ... sometimes causes duplicates, but that may be a RST problem... always put links at the END of the docstring instead of in the middle
autodoc_typehints = 'description'
typehints_defaults = "comma"
# the common names of the classes rather than the absolute paths
inheritance_alias = {
'exiftool.exiftool.ExifTool': 'exiftool.ExifTool',
'exiftool.helper.ExifToolHelper': 'exiftool.ExifToolHelper',
'exiftool.experimental.ExifToolAlpha': 'exiftool.ExifToolAlpha',
}
# help on attributes and Graphviz params:
# https://www.sphinx-doc.org/en/master/usage/extensions/inheritance.html
# https://graphs.grevian.org/reference
# https://graphviz.org/doc/info/attrs.html
#inheritance_graph_attrs = dict(rankdir="LR", size='"6.0, 8.0"', fontsize=14, ratio='compress')
inheritance_graph_attrs = dict(pad="0.2", center=True)
inheritance_node_attrs = dict(shape='box', fontsize=14, height=0.75, color='dodgerblue1', style='rounded')
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme' # pip install sphinx_rtd_theme
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# https://stackoverflow.com/questions/62904172/how-do-i-replace-view-page-source-with-edit-on-github-links-in-sphinx-rtd-th/62904217#62904217
html_context = {
#'display_github': True,
'github_user': 'sylikc',
'github_repo': 'pyexiftool',
'github_version': 'master/docs/source/',
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'PyExifTooldoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
"""
latex_documents = [
('index', 'PyExifTool.tex', u'PyExifTool Documentation',
u'Sven Marnach', 'manual'),
]
"""
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
"""
man_pages = [
('index', 'pyexiftool', u'PyExifTool Documentation',
[u'Sven Marnach'], 1)
]
"""
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
"""
texinfo_documents = [
('index', 'PyExifTool', u'PyExifTool Documentation',
u'Sven Marnach', 'PyExifTool', 'One line description of project.',
'Miscellaneous'),
]
"""
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
================================================
FILE: docs/source/examples.rst
================================================
**********************
Examples / Quick Start
**********************
.. NOTE: No tabs in this file, all spaces, to simplify examples indentation
Try it yourself: All of these examples are using the images provided in the `tests directory`_ in the source
.. _`tests directory`: https://github.com/sylikc/pyexiftool/tree/master/tests/images
Understanding input and output from PyExifTool base methods
===========================================================
Almost all methods in PyExifTool revolve around the usage of two methods from the base :py:class:`exiftool.ExifTool` class.
**It is important to understand the ouput from each of these commands**, so here's a quick summary (you can click through to the API to read more details)
.. note::
Because both methods are inherited by :py:class:`exiftool.ExifToolHelper` and :py:class:`exiftool.ExifToolAlpha`, you can call it from those classes as well.
.. _examples input params:
Input parameters
----------------
Both methods take an argument list ``*args``. Examples:
.. note::
As a general rule of thumb, if there is an **unquoted space on the command line** to *exiftool*, it's a **separate argument to the method** in PyExifTool.
If you have a working `exiftool` command-line but having trouble figuring out how to properly separate the arguments, please refer to the :ref:`FAQ `
* Calling directly:
* exiftool command-line:
.. code-block:: text
exiftool -XMPToolKit -Subject rose.jpg
* PyExifTool:
.. code-block::
execute("-XMPToolKit", "-Subject", "rose.jpg")
* Using argument unpacking of a list:
* exiftool command-line:
.. code-block:: text
exiftool -P -DateTimeOriginal="2021:01:02 03:04:05" -MakerNotes= "spaces in filename.jpg"
* PyExifTool:
.. note::
Parameters which need to be quoted on the command line generally do not need to be quoted in the parameters to PyExifTool. In fact, quoting may have unintended behavior.
In this example, *DateTimeOriginal* value is not quoted in the parameter to execute().
.. code-block::
execute(*["-P", "-DateTimeOriginal=2021:01:02 03:04:05", "-MakerNotes=", "spaces in filename.jpg"])
* Getting JSON output using argument unpacking of a list:
* exiftool command-line:
.. code-block:: text
exiftool -j -XMP:all -JFIF:JFIFVersion /path/somefile.jpg
* PyExifTool:
.. code-block::
execute_json(*["-XMP:all", "-JFIF:JFIFVersion", "/path/somefile.jpg"])
Output values
-------------
* :py:meth:`exiftool.ExifTool.execute_json`
* Returns a ``list`` of ``dict``
* Each ``dict`` is a result from a file
* Each ``dict`` contains a key "SourceFile" which points to the relative or absolute file path of file
* All other keys/value pairs are requested metadata
* :py:meth:`exiftool.ExifTool.execute`
* Returns a ``str``
* Typically used for **setting tags** as no values are returned in that case.
ExifToolHelper
==============
Using methods provided by :py:class:`exiftool.ExifToolHelper`:
ExifToolHelper provides some of the most commonly used operations most people use *exiftool* for
Getting Tags
------------
* Get all tags on a single file
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
for d in et.get_metadata("rose.jpg"):
for k, v in d.items():
print(f"Dict: {k} = {v}")
.. code-block:: text
Dict: SourceFile = rose.jpg
Dict: ExifTool:ExifToolVersion = 12.37
Dict: File:FileName = rose.jpg
Dict: File:Directory = .
Dict: File:FileSize = 4949
Dict: File:FileModifyDate = 2022:03:03 17:47:11-08:00
Dict: File:FileAccessDate = 2022:03:27 08:28:16-07:00
Dict: File:FileCreateDate = 2022:03:03 17:47:11-08:00
Dict: File:FilePermissions = 100666
Dict: File:FileType = JPEG
Dict: File:FileTypeExtension = JPG
Dict: File:MIMEType = image/jpeg
Dict: File:ImageWidth = 70
Dict: File:ImageHeight = 46
Dict: File:EncodingProcess = 0
Dict: File:BitsPerSample = 8
Dict: File:ColorComponents = 3
Dict: File:YCbCrSubSampling = 2 2
Dict: JFIF:JFIFVersion = 1 1
Dict: JFIF:ResolutionUnit = 1
Dict: JFIF:XResolution = 72
Dict: JFIF:YResolution = 72
Dict: XMP:XMPToolkit = Image::ExifTool 8.85
Dict: XMP:Subject = Röschen
Dict: Composite:ImageSize = 70 46
Dict: Composite:Megapixels = 0.00322
* Get some tags in multiple files
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
for d in et.get_tags(["rose.jpg", "skyblue.png"], tags=["FileSize", "ImageSize"]):
for k, v in d.items():
print(f"Dict: {k} = {v}")
.. code-block:: text
Dict: SourceFile = rose.jpg
Dict: File:FileSize = 4949
Dict: Composite:ImageSize = 70 46
Dict: SourceFile = skyblue.png
Dict: File:FileSize = 206
Dict: Composite:ImageSize = 64 64
Setting Tags
------------
* Setting date and time of some files to current time, overwriting file, but preserving original mod date
.. code-block::
from exiftool import ExifToolHelper
from datetime import datetime
with ExifToolHelper() as et:
now = datetime.strftime(datetime.now(), "%Y:%m:%d %H:%M:%S")
et.set_tags(
["rose.jpg", "skyblue.png"],
tags={"DateTimeOriginal": now},
params=["-P", "-overwrite_original"]
)
(*No output is returned if successful*)
* Setting keywords for a file.
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
et.set_tags(
["rose.jpg", "skyblue.png"],
tags={"Keywords": ["sunny", "nice day", "cool", "awesome"]}
)
(*No output is returned if successful*)
Exceptions
----------
By default, ExifToolHelper has some **built-in error checking**, making the methods safer to use than calling the base methods directly.
.. warning::
While "safer", the error checking isn't fool-proof. There are a lot of cases where *exiftool* just silently ignores bad input and doesn't indicate an error.
* Example using get_tags() on a list which includes a non-existent file
* ExifToolHelper with error-checking, using :py:meth:`exiftool.ExifToolHelper.get_tags`
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
print(et.get_tags(
["rose.jpg", "skyblue.png", "non-existent file.tif"],
tags=["FileSize"]
))
Output:
.. code-block:: text
Traceback (most recent call last):
File "T:\example.py", line 7, in
et.get_tags(["rose.jpg", "skyblue.png", "non-existent file.tif"], tags=["FileSize"])
File "T:\pyexiftool\exiftool\helper.py", line 353, in get_tags
ret = self.execute_json(*exec_params)
File "T:\pyexiftool\exiftool\exiftool.py", line 1030, in execute_json
result = self.execute("-j", *params) # stdout
File "T:\pyexiftool\exiftool\helper.py", line 119, in execute
raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, params)
exiftool.exceptions.ExifToolExecuteError: execute returned a non-zero exit status: 1
* ExifTool only, without error checking, using :py:meth:`exiftool.ExifTool.execute_json` (**Note how the missing file is silently ignored and doesn't show up in returned list.**)
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
print(et.get_tags(
["rose.jpg", "skyblue.png", "non-existent file.tif"],
tags=["FileSize"]
))
Output:
.. code-block:: text
[{'SourceFile': 'rose.jpg', 'File:FileSize': 4949}, {'SourceFile': 'skyblue.png', 'File:FileSize': 206}]
* Example using :py:meth:`exiftool.ExifToolHelper.get_tags` with a typo. Let's say you wanted to ``get_tags()``, but accidentally copy/pasted something and left a ``=`` character behind (deletes tag rather than getting!)...
* Using :py:meth:`exiftool.ExifToolHelper.get_tags`
.. code-block::
from exiftool import ExifToolHelper
with ExifToolHelper() as et:
print(et.get_tags(["skyblue.png"], tags=["XMP:Subject=hi"]))
Output:
.. code-block:: text
Traceback (most recent call last):
File "T:\example.py", line 7, in
print(et.get_tags(["skyblue.png"], tags=["XMP:Subject=hi"]))
File "T:\pyexiftool\exiftool\helper.py", line 341, in get_tags
self.__class__._check_tag_list(final_tags)
File "T:\pyexiftool\exiftool\helper.py", line 574, in _check_tag_list
raise ExifToolTagNameError(t)
exiftool.exceptions.ExifToolTagNameError: Invalid Tag Name found: "XMP:Subject=hi"
* Using :py:meth:`exiftool.ExifTool.execute_json`. It still raises an exception, but more cryptic and difficult to debug
.. code-block::
from exiftool import ExifTool
with ExifTool() as et:
print(et.execute_json(*["-XMP:Subject=hi"] + ["skyblue.png"]))
Output:
.. code-block:: text
Traceback (most recent call last):
File "T:\example.py", line 7, in
print(et.execute_json(*["-XMP:Subject=hi"] + ["skyblue.png"]))
File "T:\pyexiftool\exiftool\exiftool.py", line 1052, in execute_json
raise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params)
exiftool.exceptions.ExifToolOutputEmptyError: execute_json expected output on stdout but got none
* Using :py:meth:`exiftool.ExifTool.execute`. **No errors, but you have now written to the file instead of reading from it!**
.. code-block::
from exiftool import ExifTool
with ExifTool() as et:
print(et.execute(*["-XMP:Subject=hi"] + ["skyblue.png"]))
Output:
.. code-block:: text
1 image files updated
ExifTool
========
Using methods provided by :py:class:`exiftool.ExifTool`
Calling execute() or execute_json() provides raw functionality for advanced use cases. Use with care!
.. TODO show some ExifTool and ExifToolHelper use cases for common exiftool operations
.. TODO show some Advanced use cases, and maybe even some don't-do-this-even-though-you-can cases (like using params for tags)
================================================
FILE: docs/source/faq.rst
================================================
**************************
Frequently Asked Questions
**************************
PyExifTool output is different from the exiftool command line
=============================================================
One of the most frequently asked questions relates to the *default output* of PyExifTool.
For example, using the `rose.jpg in tests`_, let's get **all JFIF tags**:
Default exiftool output
-----------------------
$ ``exiftool -JFIF:all rose.jpg``
.. code-block:: text
JFIF Version : 1.01
Resolution Unit : inches
X Resolution : 72
Y Resolution : 72
.. _`rose.jpg in tests`: https://github.com/sylikc/pyexiftool/blob/master/tests/files/rose.jpg
Default PyExifTool output
-------------------------
from PyExifTool, using the following code:
.. code-block::
import exiftool
with exiftool.ExifTool() as et:
print(et.execute("-JFIF:all", "rose.jpg"))
Output:
.. code-block:: text
[JFIF] JFIF Version : 1 1
[JFIF] Resolution Unit : 1
[JFIF] X Resolution : 72
[JFIF] Y Resolution : 72
What's going on?
----------------
The reason for the different default output is that PyExifTool, by default, includes two arguments which make *exiftool* easier to use: ``-G, -n``.
.. note::
The ``-n`` disables *print conversion* which displays **raw tag values**, making the output more **machine-parseable**.
When *print conversion* is enabled, *some* raw values may be translated to prettier **human-readable** text.
.. note::
The ``-G`` enables *group name (level 1)* option which displays a group in the output to help disambiguate tags with the same name in different groups.
For example, *-DateCreated* can be ambiguous if both *-IPTC:DateCreated* and *-XMP:DateCreated* exists and have different values. ``-G`` would display which one was returned by *exiftool*.
Read the documentation for the ExifTool constructor ``common_args`` parameter for more details: :py:meth:`exiftool.ExifTool.__init__`.
(You can also change ``common_args`` on an existing instance using :py:attr:`exiftool.ExifTool.common_args`, as long as the subprocess is not :py:attr:`exiftool.ExifTool.running`)
Ways to make the ouptut match
-----------------------------
So if you want to have the ouput match (*useful for debugging*) between PyExifTool and exiftool, either:
* **Enable print conversion on exiftool command line**:
$ ``exiftool -G -n -JFIF:all rose.jpg``
.. code-block:: text
[JFIF] JFIF Version : 1 1
[JFIF] Resolution Unit : 1
[JFIF] X Resolution : 72
[JFIF] Y Resolution : 72
* **Disable print conversion and group name in PyExifTool**:
.. code-block::
import exiftool
with exiftool.ExifTool(common_args=None) as et:
print(et.execute("-JFIF:all", "rose.jpg"))
Output:
.. code-block:: text
JFIF Version : 1.01
Resolution Unit : inches
X Resolution : 72
Y Resolution : 72
.. _shlex split:
I can run this on the command-line but it doesn't work in PyExifTool
====================================================================
A frequent problem encountered by first-time users, is figuring out how to properly split their arguments into a call to PyExifTool.
As noted in the :ref:`Quick Start Examples `:
If there is an **unquoted space on the command line** to *exiftool*, it's a **separate argument to the method** in PyExifTool.
So, what does this look like in practice?
Use `Python's shlex library`_ as a quick and easy way to figure out what the parameters to :py:meth:`exiftool.ExifTool.execute` or :py:meth:`exiftool.ExifTool.execute_json` should be.
* Sample exiftool command line (with multiple quoted and unquoted parameters):
.. code-block:: text
exiftool -v0 -preserve -overwrite_original -api largefilesupport=1 -api "QuickTimeUTC=1" "-EXIF:DateTimeOriginal+=1:2:3 4:5:6" -XMP:DateTimeOriginal="2006:05:04 03:02:01" -gpsaltituderef="Above Sea Level" -make= test.mov
* Using ``shlex`` to figure out the right argument list:
.. code-block::
import shlex, exiftool
with exiftool.ExifToolHelper() as et:
params = shlex.split('-v0 -preserve -overwrite_original -api largefilesupport=1 "-EXIF:DateTimeOriginal+=1:2:3 4:5:6" -XMP:DateTimeOriginal="2006:05:04 03:02:01" -gpsaltituderef="Above Sea Level" -make= test.mov')
print(params)
# Output: ['-v0', '-preserve', '-overwrite_original', '-api', 'largefilesupport=1', '-api', 'QuickTimeUTC=1', '-EXIF:DateTimeOriginal+=1:2:3 4:5:6', '-XMP:DateTimeOriginal=2006:05:04 03:02:01', '-gpsaltituderef=Above Sea Level', '-make=', 'test.mov']
et.execute(*params)
.. note::
``shlex.split()`` is a useful *tool to simplify discovery* of the correct arguments needed to call PyExifTool.
However, since spliting and constructing immutable strings in Python is **slower than building the parameter list properly**, this method is *only recommended for* **debugging**!
.. _`Python's shlex library`: https://docs.python.org/library/shlex.html
.. _set_json_loads faq:
PyExifTool json turns some text fields into numbers
===================================================
A strange behavior of *exiftool* is documented in the `exiftool documentation`_::
-j[[+]=JSONFILE] (-json)
Note that ExifTool quotes JSON values only if they don't look like numbers
(regardless of the original storage format or the relevant metadata specification).
.. _`exiftool documentation`: https://exiftool.org/exiftool_pod.html#OPTIONS
This causes a peculiar behavior if you set a text metadata field to a string that looks like a number:
.. code-block::
import exiftool
with exiftool.ExifToolHelper() as et:
# Comment is a STRING field
et.set_tags("rose.jpg", {"Comment": "1.10"}) # string: "1.10" != "1.1"
# FocalLength is a FLOAT field
et.set_tags("rose.jpg", {"FocalLength": 1.10}) # float: 1.10 == 1.1
print(et.get_tags("rose.jpg", ["Comment", "FocalLength"]))
# Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': 1.1, 'EXIF:FocalLength': 1.1}]
Workaround to enable output as string
-------------------------------------
There is no universal fix which wouldn't affect other behaviors in PyExifTool, so this is an advanced workaround if you encounter this specific problem.
PyExifTool does not do any processing on the fields returned by *exiftool*. In effect, what is returned is processed directly by ``json.loads()`` by default.
You can change the behavior of the json string parser, or specify a different one using :py:meth:`exiftool.ExifTool.set_json_loads`.
The `documentation of CPython's json.load`_ allows ``parse_float`` to be any parser of choice when a float is encountered in a JSON file. Thus, you can force the float to be interpreted as a string.
However, as you can see below, it also *changes the behavior of all float fields*.
.. _`documentation of CPython's json.load`: https://docs.python.org/3/library/json.html#json.load
.. code-block::
import exiftool, json
with exiftool.ExifToolHelper() as et:
et.set_json_loads(json.loads, parse_float=str)
# Comment is a STRING field
et.set_tags("rose.jpg", {"Comment": "1.10"}) # string: "1.10" == "1.10"
# FocalLength is a FLOAT field
et.set_tags("rose.jpg", {"FocalLength": 1.10}) # float: 1.1 != "1.1"
print(et.get_tags("rose.jpg", ["Comment", "FocalLength"]))
# Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': '1.10', 'EXIF:FocalLength': '1.1'}]
.. warning::
Unfortunately you can either change all float fields to a string, or possibly lose some float precision when working with floats in string metadata fields.
There isn't any known universal workaround which wouldn't break one thing or the other, as it is an underlying *exiftool* quirk.
There are other edge cases which may exhibit quirky behavior when storing numbers and whitespace only to text fields (See `test cases related to numeric tags`_). Since PyExifTool cannot accommodate all possible edge cases,
this workaround will allow you to configure PyExifTool to work in your environment!
.. _`test cases related to numeric tags`: https://github.com/sylikc/pyexiftool/blob/master/tests/test_helper_tags_float.py
I would like to use a faster json string parser
===============================================
By default, PyExifTool uses the built-in ``json`` library to load the json string returned by *exiftool*. If you would like to use an alternate library, set it manually using :py:meth:`exiftool.ExifTool.set_json_loads`
.. code-block::
import exiftool, json
with exiftool.ExifToolHelper() as et:
et.set_json_loads(ujson.loads)
...
.. note::
In PyExifTool version before 0.5.6, ``ujson`` was supported automatically if the package was installed.
To support any possible alternative JSON library, this behavior has now been changed and it must be enabled manually.
I'm getting an error! How do I debug PyExifTool output?
=======================================================
To assist debugging, ExifTool has a ``logger`` in the constructor :py:meth:`exiftool.ExifTool.__init__`. You can also specify the logger after constructing the object by using the :py:attr:`exiftool.ExifTool.logger` property.
First construct the logger object. The example below using the most common way to construct using ``getLogger(__name__)``. See more examples on `Python logging - Advanced Logging Tutorial`_
.. _`Python logging - Advanced Logging Tutorial`: https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial
Example usage:
.. code-block::
import logging
import exiftool
logging.basicConfig(level=logging.DEBUG)
with exiftool.ExifToolHelper(logger=logging.getLogger(__name__)) as et:
et.execute("missingfile.jpg",)
================================================
FILE: docs/source/index.rst
================================================
.. PyExifTool documentation master file, created by
sphinx-quickstart on Thu Apr 12 17:42:54 2012.
PyExifTool -- Python wrapper for Phil Harvey's ExifTool
=======================================================
.. include:: ../../README.rst
:start-after: BLURB_START
:end-before: BLURB_END
.. toctree::
:maxdepth: 2
:glob:
:caption: Contents:
intro
package
installation
examples
reference/*
FAQ
autoapi/*
Source code on GitHub
.. maintenance/*
.. not public at the moment, at least it doesn't have to be in the TOC (adds unnecessary clutter)
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
================================================
FILE: docs/source/installation.rst
================================================
************
Installation
************
.. include:: ../../README.rst
:start-after: INSTALLATION_START
:end-before: INSTALLATION_END
================================================
FILE: docs/source/intro.rst
================================================
************
Introduction
************
.. _introduction:
.. include:: ../../README.rst
:start-after: DESCRIPTION_START
:end-before: DESCRIPTION_END
Concepts
========
As noted in the :ref:`introduction `, PyExifTool is used to **communicate** with an instance of the external ExifTool process.
.. note::
PyExifTool cannot do what ExifTool does not do. If you're not yet familiar with the capabilities of PH's ExifTool, please head over to `ExifTool by Phil Harvey`_ homepage and read up on how to use it, and what it's capable of.
.. _ExifTool by Phil Harvey: https://exiftool.org/
What PyExifTool Is
------------------
* ... is a wrapper for PH's Exiftool, hence it can do everything PH's ExifTool can do.
* ... is a library which adds some helper functionality around ExifTool to make it easier to work with in Python.
* ... is extensible and you can add functionality on top of the base class for your use case.
* ... is supported on any platform which PH's ExifTool runs
What PyExifTool Is NOT
----------------------
* ... is NOT a direct subtitute for Phil Harvey's ExifTool. The `exiftool` executable must still be installed and available for PyExifTool to use.
* ... is NOT a library which does direct image manipulation (ex. Python Pillow_).
.. _Pillow: https://pillow.readthedocs.io/en/stable/
Nomenclature
============
PyExifTool's namespace is *exiftool*. Since library name the same name of the tool it's meant to interface with, it can cause some ambiguity when describing it in docs.
Hence, here's some common nomenclature used.
Because the term `exiftool` is overloaded (lowercase, CapWords case, ...) and can mean several things:
* `PH's ExifTool` = Phil Harvey's ExifTool
* ``ExifTool`` in context usually implies ``exiftool.ExifTool``
* `exiftool` when used alone almost always refers to `PH's ExifTool`'s command line executable. (While Windows is supported with `exiftool.exe` the Linux nomenclature is used throughout the docs)
================================================
FILE: docs/source/maintenance/release-process.rst
================================================
***************
Release Process
***************
This page documents the steps to be taken to release a new version of PyExifTool.
Source Preparation
==================
#. Update the version number in ``exiftool/__init__.py``
#. Update the docs copyright year ``docs/source/conf.py`` and in source files
#. Add any changelog entries to ``CHANGELOG.md``
#. Run Tests
#. Generate docs
#. Commit and push the changes.
#. Check that the tests passed on GitHub.
Pre-Requisites
==============
Make sure the latest packages are installed.
#. pip: ``python -m pip install --upgrade pip``
#. build tools: ``python -m pip install --upgrade setuptools build``
#. for uploading to PyPI: ``python -m pip install --upgrade twine``
Run Tests
=========
#. Run in standard unittest: ``python -m unittest -v``
#. Run in PyTest: ``scripts\pytest.bat``
Build and Check
===============
#. Build package: ``python -m build``
#. `Validating reStructuredText markup`_: ``python -m twine check dist/*``
.. _Validating reStructuredText markup: https://packaging.python.org/guides/making-a-pypi-friendly-readme/#validating-restructuredtext-markup
Upload to Test PyPI
===================
Set up the ``$HOME/.pypirc`` (Linux) or ``%UserProfile%\.pypirc`` (Windows)
#. ``python -m twine upload --repository testpypi dist/*``
#. Check package uploaded properly: `TestPyPI PyExifTool`_
#. Create a temporary venv to test PyPI and run tests
#. ``python -m venv tmp``
#. Activate venv
#. ``python -m pip install -U -i https://test.pypi.org/simple/ PyExifTool``
* If there is an error with SSL verification, just trust it: ``python -m pip install --trusted-host test-files.pythonhosted.org -U -i https://test.pypi.org/simple/ PyExifTool``
* If you want to test a specific version, can specify as ``PyExifTool==``, otherwise it installs the latest by default
#. Make sure exiftool is found on PATH
#. Run tests: ``python -m pytext -v ``
#. Examine files installed to make sure it looks ok
#. Cleanup: ``python -m pip uninstall PyExifTool``, then delete temp venv
.. _`TestPyPI PyExifTool`: https://test.pypi.org/project/PyExifTool/#history
Release
=======
#. Be very sure all the tests pass and the package is good, because `PyPI does not allow for a filename to be reused`_
#. Release to production PyPI: ``python -m twine upload dist/*``
#. If needed, create a tag, and a GitHub release with the *whl* file
.. code-block:: bash
git tag -a vX.X.X
git push --tags
.. _PyPI does not allow for a filename to be reused: https://pypi.org/help/#file-name-reuse
================================================
FILE: docs/source/package.rst
================================================
****************
Package Overview
****************
All classes live under the PyExifTool library namespace: ``exiftool``
Design
======
.. include:: ../../README.rst
:start-after: DESIGN_INFO_START
:end-before: DESIGN_INFO_END
.. inheritance-diagram:: exiftool.ExifToolAlpha
.. include:: ../../README.rst
:start-after: DESIGN_CLASS_START
:end-before: DESIGN_CLASS_END
Fork Origins / Brief History
============================
.. include:: ../../README.rst
:start-after: HISTORY_START
:end-before: HISTORY_END
License
=======
.. include:: ../../README.rst
:start-after: LICENSE_START
:end-before: LICENSE_END
================================================
FILE: docs/source/reference/1-exiftool.rst
================================================
***********************
Class exiftool.ExifTool
***********************
.. inheritance-diagram:: exiftool.ExifTool
.. autoapimodule:: exiftool.ExifTool
:members:
:undoc-members:
:special-members: __init__
:show-inheritance:
.. :private-members:
.. currently excluding private members
================================================
FILE: docs/source/reference/2-helper.rst
================================================
*****************************
Class exiftool.ExifToolHelper
*****************************
.. inheritance-diagram:: exiftool.ExifToolHelper
.. autoapimodule:: exiftool.ExifToolHelper
:members:
:undoc-members:
:special-members: __init__
:show-inheritance:
================================================
FILE: docs/source/reference/3-alpha.rst
================================================
****************************
Class exiftool.ExifToolAlpha
****************************
.. inheritance-diagram:: exiftool.ExifToolAlpha
.. autoapimodule:: exiftool.ExifToolAlpha
:members:
:undoc-members:
:special-members: __init__
:show-inheritance:
================================================
FILE: exiftool/__init__.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
PyExifTool is a Python library to communicate with an instance of Phil
Harvey's excellent ExifTool_ command-line application. The library
provides the class :py:class:`ExifTool` that runs the command-line
tool in batch mode and features methods to send commands to that
program, including methods to extract meta-information from one or
more image files. Since ``exiftool`` is run in batch mode, only a
single instance needs to be launched and can be reused for many
queries. This is much more efficient than launching a separate
process for every single query.
.. _ExifTool: https://exiftool.org
The source code can be checked out from the github repository with
::
git clone git://github.com/sylikc/pyexiftool.git
Alternatively, you can download a tarball_. There haven't been any
releases yet.
.. _tarball: https://github.com/sylikc/pyexiftool/tarball/master
PyExifTool is licenced under GNU GPL version 3 or later, or BSD license.
Example usage::
import exiftool
files = ["a.jpg", "b.png", "c.tif"]
with exiftool.ExifToolHelper() as et:
metadata = et.get_metadata(files)
for d in metadata:
print("{:20.20} {:20.20}".format(d["SourceFile"],
d["EXIF:DateTimeOriginal"]))
"""
# version number using Semantic Versioning 2.0.0 https://semver.org/
# may not be PEP-440 compliant https://www.python.org/dev/peps/pep-0440/#semantic-versioning
__version__ = "0.5.6"
# while we COULD import all the exceptions into the base library namespace,
# it's best that it lives as exiftool.exceptions, to not pollute the base namespace
from . import exceptions
# make all of the original exiftool stuff available in this namespace
from .exiftool import ExifTool
from .helper import ExifToolHelper
from .experimental import ExifToolAlpha
# an old feature of the original class that exposed this variable at the library level
# TODO may remove and deprecate at a later time
#from .constants import DEFAULT_EXECUTABLE
================================================
FILE: exiftool/constants.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
This submodule defines constants which are used by other modules in the package
"""
import sys
##################################
############# HELPERS ############
##################################
# instead of comparing everywhere sys.platform, do it all here in the constants (less typo chances)
# True if Windows
PLATFORM_WINDOWS: bool = (sys.platform == 'win32')
"""sys.platform check, set to True if Windows"""
# Prior to Python 3.3, the value for any Linux version is always linux2; after, it is linux.
# https://stackoverflow.com/a/13874620/15384838
PLATFORM_LINUX: bool = (sys.platform == 'linux' or sys.platform == 'linux2')
"""sys.platform check, set to True if Linux"""
##################################
####### PLATFORM DEFAULTS ########
##################################
# specify the extension so exiftool doesn't default to running "exiftool.py" on windows (which could happen)
DEFAULT_EXECUTABLE: str = "exiftool.exe" if PLATFORM_WINDOWS else "exiftool"
"""The name of the default executable to run.
``exiftool.exe`` (Windows) or ``exiftool`` (Linux/Mac/non-Windows platforms)
By default, the executable is searched for on one of the paths listed in the
``PATH`` environment variable. If it's not on the ``PATH``, a full path should be specified in the
``executable`` argument of the ExifTool constructor (:py:meth:`exiftool.ExifTool.__init__`).
"""
"""
# flipped the if/else so that the sphinx documentation shows "exiftool" rather than "exiftool.exe"
if not PLATFORM_WINDOWS: # pytest-cov:windows: no cover
DEFAULT_EXECUTABLE = "exiftool"
else:
DEFAULT_EXECUTABLE = "exiftool.exe"
"""
##################################
####### STARTUP CONSTANTS ########
##################################
# for Windows STARTUPINFO
SW_FORCEMINIMIZE: int = 11
"""Windows ShowWindow constant from win32con
Indicates the launched process window should start minimized
"""
# for Linux preexec_fn
PR_SET_PDEATHSIG: int = 1
"""Extracted from linux/prctl.h
Allows a kill signal to be sent to child processes when the parent unexpectedly dies
"""
##################################
######## GLOBAL DEFAULTS #########
##################################
DEFAULT_BLOCK_SIZE: int = 4096
"""The default block size when reading from exiftool. The standard value
should be fine, though other values might give better performance in
some cases."""
EXIFTOOL_MINIMUM_VERSION: str = "12.15"
"""this is the minimum *exiftool* version required for current version of PyExifTool
* 8.40 / 8.60 (production): implemented the -stay_open flag
* 12.10 / 12.15 (production): implemented exit status on -echo4
"""
================================================
FILE: exiftool/exceptions.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
This submodule holds all of the custom exceptions which can be raised by PyExifTool
"""
########################################################
#################### Base Exception ####################
########################################################
class ExifToolException(Exception):
"""
Generic Base class for all ExifTool error classes
"""
#############################################################
#################### Process State Error ####################
#############################################################
class ExifToolProcessStateError(ExifToolException):
"""
Base class for all errors related to the invalid state of `exiftool` subprocess
"""
class ExifToolRunning(ExifToolProcessStateError):
"""
ExifTool is already running
"""
def __init__(self, message: str):
super().__init__(f"ExifTool instance is running: {message}")
class ExifToolNotRunning(ExifToolProcessStateError):
"""
ExifTool is not running
"""
def __init__(self, message: str):
super().__init__(f"ExifTool instance not running: {message}")
###########################################################
#################### Execute Exception ####################
###########################################################
# all of these exceptions are related to something regarding execute
class ExifToolExecuteException(ExifToolException):
"""
This is the base exception class for all execute() associated errors.
This exception is never returned directly from any method, but provides common interface for subclassed errors.
(mimics the signature of :py:class:`subprocess.CalledProcessError`)
:attribute cmd: Parameters sent to *exiftool* which raised the error
:attribute returncode: Exit Status (Return code) of the ``execute()`` command which raised the error
:attribute stdout: STDOUT stream returned by the command which raised the error
:attribute stderr: STDERR stream returned by the command which raised the error
"""
def __init__(self, message, exit_status, cmd_stdout, cmd_stderr, params):
super().__init__(message)
self.returncode: int = exit_status
self.cmd: list = params
self.stdout: str = cmd_stdout
self.stderr: str = cmd_stderr
class ExifToolExecuteError(ExifToolExecuteException):
"""
ExifTool executed the command but returned a non-zero exit status.
.. note::
There is a similarly named :py:exc:`ExifToolExecuteException` which this Error inherits from.
That is a base class and never returned directly. This is what is raised.
"""
def __init__(self, exit_status, cmd_stdout, cmd_stderr, params):
super().__init__(f"execute returned a non-zero exit status: {exit_status}", exit_status, cmd_stdout, cmd_stderr, params)
########################################################
#################### JSON Exception ####################
########################################################
class ExifToolOutputEmptyError(ExifToolExecuteException):
"""
ExifTool execute_json() expected output, but execute() did not return any output on stdout
This is an error, because if you expect no output, don't use execute_json()
.. note::
Only thrown by execute_json()
"""
def __init__(self, exit_status, cmd_stdout, cmd_stderr, params):
super().__init__("execute_json expected output on stdout but got none", exit_status, cmd_stdout, cmd_stderr, params)
class ExifToolJSONInvalidError(ExifToolExecuteException):
"""
ExifTool execute_json() expected valid JSON to be returned, but got invalid JSON.
This is an error, because if you expect non-JSON output, don't use execute_json()
.. note::
Only thrown by execute_json()
"""
def __init__(self, exit_status, cmd_stdout, cmd_stderr, params):
super().__init__("execute_json received invalid JSON output from exiftool", exit_status, cmd_stdout, cmd_stderr, params)
#########################################################
#################### Other Exception ####################
#########################################################
class ExifToolVersionError(ExifToolException):
"""
Generic Error to represent some version mismatch.
PyExifTool is coded to work with a range of exiftool versions. If the advanced params change in functionality and break PyExifTool, this error will be thrown
"""
class ExifToolTagNameError(ExifToolException):
"""
ExifToolHelper found an invalid tag name
This error is raised when :py:attr:`exiftool.ExifToolHelper.check_tag_names` is enabled, and a bad tag is provided to a method
"""
def __init__(self, bad_tag):
super().__init__(f"Invalid Tag Name found: \"{bad_tag}\"")
================================================
FILE: exiftool/exiftool.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
This submodule contains the core ``ExifTool`` class of PyExifTool
.. note::
:py:class:`exiftool.helper.ExifTool` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifTool`
"""
# ---------- standard Python imports ----------
import select
import subprocess
import os
import shutil
from pathlib import Path # requires Python 3.4+
import random
import locale
import warnings
import json # NOTE: to use other json libraries (simplejson/ujson/orjson/...), see :py:meth:`set_json_loads()`
# for the pdeathsig
import signal
import ctypes
# ---------- Typing Imports ----------
# for static analysis / type checking - Python 3.5+
from collections.abc import Callable
from typing import Optional, List, Union
# ---------- Library Package Imports ----------
from . import constants
from .exceptions import ExifToolVersionError, ExifToolRunning, ExifToolNotRunning, ExifToolOutputEmptyError, ExifToolJSONInvalidError
# ======================================================================================================================
# constants to make typos obsolete!
ENCODING_UTF8: str = "utf-8"
#ENCODING_LATIN1: str = "latin-1"
# ======================================================================================================================
def _set_pdeathsig(sig) -> Optional[Callable]:
"""
Use this method in subprocess.Popen(preexec_fn=set_pdeathsig()) to make sure,
the exiftool childprocess is stopped if this process dies.
However, this only works on linux.
"""
if constants.PLATFORM_LINUX:
def callable_method():
libc = ctypes.CDLL("libc.so.6")
return libc.prctl(constants.PR_SET_PDEATHSIG, sig)
return callable_method
else:
return None # pragma: no cover
# ======================================================================================================================
def _get_buffer_end(buffer_list: List[bytes], bytes_needed: int) -> bytes:
""" Given a list of bytes objects, return the equivalent of
b"".join(buffer_list)[-bytes_needed:]
but without having to concatenate the entire list.
"""
if bytes_needed < 1:
return b"" # pragma: no cover
buf_chunks = []
for buf in reversed(buffer_list):
buf_tail = buf[-bytes_needed:]
buf_chunks.append(buf_tail)
bytes_needed -= len(buf_tail)
if bytes_needed <= 0:
break
buf_tail_joined = b"".join(reversed(buf_chunks))
return buf_tail_joined
def _read_fd_endswith(fd, b_endswith: bytes, block_size: int) -> bytes:
""" read an fd and keep reading until it endswith the seq_ends
this allows a consolidated read function that is platform indepdent
if you're not careful, on windows, this will block
"""
output_list: List[bytes] = []
# if we're only looking at the last few bytes, make it meaningful. 4 is max size of \r\n? (or 2)
# this value can be bigger to capture more bytes at the "tail" of the read, but if it's too small, the whitespace might miss the detection
endswith_count = len(b_endswith) + 4
# I believe doing a splice, then a strip is more efficient in memory hence the original code did it this way.
# need to benchmark to see if in large strings, strip()[-endswithcount:] is more expensive or not
while not _get_buffer_end(output_list, endswith_count).strip().endswith(b_endswith):
if constants.PLATFORM_WINDOWS:
# windows does not support select() for anything except sockets
# https://docs.python.org/3.7/library/select.html
output_list.append(os.read(fd, block_size))
else: # pytest-cov:windows: no cover
# this does NOT work on windows... and it may not work on other systems... in that case, put more things to use the original code above
inputready, outputready, exceptready = select.select([fd], [], [])
for i in inputready:
if i == fd:
output_list.append(os.read(fd, block_size))
return b"".join(output_list)
# ======================================================================================================================
class ExifTool(object):
"""Run the `exiftool` command-line tool and communicate with it.
Use ``common_args`` to enable/disable print conversion by specifying/omitting ``-n``, respectively.
This determines whether exiftool should perform print conversion,
which prints values in a human-readable way but
may be slower. If print conversion is enabled, appending ``#`` to a tag
name disables the print conversion for this particular tag.
See `Exiftool print conversion FAQ`_ for more details.
.. _Exiftool print conversion FAQ: https://exiftool.org/faq.html#Q6
Some methods of this class are only available after calling
:py:meth:`run()`, which will actually launch the *exiftool* subprocess.
To avoid leaving the subprocess running, make sure to call
:py:meth:`terminate()` method when finished using the instance.
This method will also be implicitly called when the instance is
garbage collected, but there are circumstance when this won't ever
happen, so you should not rely on the implicit process
termination. Subprocesses won't be automatically terminated if
the parent process exits, so a leaked subprocess will stay around
until manually killed.
A convenient way to make sure that the subprocess is terminated is
to use the :py:class:`ExifTool` instance as a context manager::
with ExifTool() as et:
...
.. warning::
Note that options and parameters are not checked. There is no error handling or validation of options passed to *exiftool*.
Nonsensical options are mostly silently ignored by exiftool, so there's not
much that can be done in that regard. You should avoid passing
non-existent files to any of the methods, since this will lead
to undefined behaviour.
"""
##############################################################################
#################################### INIT ####################################
##############################################################################
# ----------------------------------------------------------------------------------------------------------------------
def __init__(self,
executable: Optional[str] = None,
common_args: Optional[List[str]] = ["-G", "-n"],
win_shell: bool = False,
config_file: Optional[Union[str, Path]] = None,
encoding: Optional[str] = None,
logger = None) -> None:
"""
:param executable: Specify file name of the *exiftool* executable if it is in your ``PATH``. Otherwise, specify the full path to the ``exiftool`` executable.
Passed directly into :py:attr:`executable` property.
.. note::
The default value :py:attr:`exiftool.constants.DEFAULT_EXECUTABLE` will only work if the executable is in your ``PATH``.
:type executable: str, or None to use default
:param common_args:
Pass in additional parameters for the stay-open instance of exiftool.
Defaults to ``["-G", "-n"]`` as this is the most common use case.
* ``-G`` (groupName level 1 enabled) separates the output with *groupName:tag* to disambiguate same-named tags under different groups.
* ``-n`` (print conversion disabled) improves the speed and consistency of output, and is more machine-parsable
Passed directly into :py:attr:`common_args` property.
.. note::
Depending on your use case, there may be other useful grouping levels and options. Search `Phil Harvey's exiftool documentation`_ for **groupNames** and **groupHeadings** to get more info.
.. _`Phil Harvey's exiftool documentation`: https://exiftool.org/exiftool_pod.html
:type common_args: list of str, or None.
:param bool win_shell: (Windows only) Minimizes the exiftool process.
.. note::
This parameter may be deprecated in the future
:param config_file:
File path to ``-config`` parameter when starting exiftool process.
Passed directly into :py:attr:`config_file` property.
:type config_file: str, Path, or None
:param encoding: Specify encoding to be used when communicating with
exiftool process. By default, will use ``locale.getpreferredencoding()``
Passed directly into :py:attr:`encoding` property.
:param logger: Set a custom logger to log status and debug messages to.
Passed directly into :py:attr:`logger` property.
"""
# --- default settings / declare member variables ---
self._running: bool = False # is it running?
"""A Boolean value indicating whether this instance is currently
associated with a running subprocess."""
self._win_shell: bool = win_shell # do you want to see the shell on Windows?
self._process = None # this is set to the process to interact with when _running=True
self._ver: Optional[str] = None # this is set to be the exiftool -v -ver when running
self._last_stdout: Optional[str] = None # previous output
self._last_stderr: Optional[str] = None # previous stderr
self._last_status: Optional[int] = None # previous exit status from exiftool (look up EXIT STATUS in exiftool documentation for more information)
self._block_size: int = constants.DEFAULT_BLOCK_SIZE # set to default block size
# these are set via properties
self._executable: Union[str, Path] = constants.DEFAULT_EXECUTABLE # executable absolute path (default set to just the executable name, so it can't be None)
self._config_file: Optional[str] = None # config file that can only be set when exiftool is not running
self._common_args: Optional[List[str]] = None
self._logger = None
self._encoding: Optional[str] = None
self._json_loads: Callable = json.loads # variable points to the actual callable method
self._json_loads_kwargs: dict = {} # default optional params to pass into json.loads() call
# --- run external library initialization code ---
random.seed(None) # initialize random number generator
# --- set variables via properties (which do the error checking) --
# set first, so that debug and info messages get logged
self.logger = logger
# use the passed in parameter, or the default if not set
# error checking is done in the property.setter
self.executable = executable or constants.DEFAULT_EXECUTABLE
self.encoding = encoding
self.common_args = common_args
# set the property, error checking happens in the property.setter
self.config_file = config_file
#######################################################################################
#################################### MAGIC METHODS ####################################
#######################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def __enter__(self):
self.run()
return self
# ----------------------------------------------------------------------------------------------------------------------
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
if self.running:
self.terminate()
# ----------------------------------------------------------------------------------------------------------------------
def __del__(self) -> None:
if self.running:
# indicate that __del__ has been started - allows running alternate code path in terminate()
self.terminate(_del=True)
########################################################################################
#################################### PROPERTIES R/w ####################################
########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
@property
def executable(self) -> Union[str, Path]:
"""
Path to *exiftool* executable.
:getter: Returns current exiftool path
:setter: Specify just the executable name, or an absolute path to the executable.
If path given is not absolute, searches environment ``PATH``.
.. note::
Setting is only available when exiftool process is not running.
:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)
:type: str, Path
"""
return self._executable
@executable.setter
def executable(self, new_executable: Union[str, Path]) -> None:
# cannot set executable when process is running
if self.running:
raise ExifToolRunning("Cannot set new executable")
abs_path: Optional[str] = None
# in testing, shutil.which() will work if a complete path is given,
# but this isn't clear from documentation, so we explicitly check and
# don't search if path exists
if Path(new_executable).exists():
abs_path = new_executable
else:
# Python 3.3+ required
abs_path = shutil.which(new_executable)
if abs_path is None:
raise FileNotFoundError(f'"{new_executable}" is not found, on path or as absolute path')
# absolute path is returned
self._executable = str(abs_path)
if self._logger: self._logger.info(f"Property 'executable': set to \"{abs_path}\"")
# ----------------------------------------------------------------------------------------------------------------------
@property
def encoding(self) -> Optional[str]:
"""
Encoding of Popen() communication with *exiftool* process.
:getter: Returns current encoding setting
:setter: Set a new encoding.
* If *new_encoding* is None, will detect it from ``locale.getpreferredencoding(do_setlocale=False)`` (do_setlocale is set to False as not to affect the caller).
* Default to ``utf-8`` if nothing is returned by ``getpreferredencoding``
.. warning::
Property setter does NOT validate the encoding for validity. It is passed verbatim into subprocess.Popen()
.. note::
Setting is only available when exiftool process is not running.
:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)
"""
return self._encoding
@encoding.setter
def encoding(self, new_encoding: Optional[str]) -> None:
# cannot set encoding when process is running
if self.running:
raise ExifToolRunning("Cannot set new encoding")
# auto-detect system specific
self._encoding = new_encoding or (locale.getpreferredencoding(do_setlocale=False) or ENCODING_UTF8)
# ----------------------------------------------------------------------------------------------------------------------
@property
def block_size(self) -> int:
"""
Block size for communicating with *exiftool* subprocess. Used when reading from the I/O pipe.
:getter: Returns current block size
:setter: Set a new block_size. Does basic error checking to make sure > 0.
:raises ValueError: If new block size is invalid
:type: int
"""
return self._block_size
@block_size.setter
def block_size(self, new_block_size: int) -> None:
if new_block_size <= 0:
raise ValueError("Block Size doesn't make sense to be <= 0")
self._block_size = new_block_size
if self._logger: self._logger.info(f"Property 'block_size': set to \"{new_block_size}\"")
# ----------------------------------------------------------------------------------------------------------------------
@property
def common_args(self) -> Optional[List[str]]:
"""
Common Arguments executed with every command passed to *exiftool* subprocess
This is the parameter `-common_args`_ that is passed when the *exiftool* process is STARTED
Read `Phil Harvey's ExifTool documentation`_ to get further information on what options are available / how to use them.
.. _-common_args: https://exiftool.org/exiftool_pod.html#Advanced-options
.. _Phil Harvey's ExifTool documentation: https://exiftool.org/exiftool_pod.html
:getter: Returns current common_args list
:setter: If ``None`` is passed in, sets common_args to ``[]``. Otherwise, sets the given list without any validation.
.. warning::
No validation is done on the arguments list. It is passed verbatim to *exiftool*. Invalid options or combinations may result in undefined behavior.
.. note::
Setting is only available when exiftool process is not running.
:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)
:raises TypeError: If setting is not a list
:type: list[str], None
"""
return self._common_args
@common_args.setter
def common_args(self, new_args: Optional[List[str]]) -> None:
if self.running:
raise ExifToolRunning("Cannot set new common_args")
if new_args is None:
self._common_args = []
elif isinstance(new_args, list):
# default parameters to exiftool
# -n = disable print conversion (speedup)
self._common_args = new_args
else:
raise TypeError("common_args not a list of strings")
if self._logger: self._logger.info(f"Property 'common_args': set to \"{self._common_args}\"")
# ----------------------------------------------------------------------------------------------------------------------
@property
def config_file(self) -> Optional[Union[str, Path]]:
"""
Path to config file.
See `ExifTool documentation for -config`_ for more details.
:getter: Returns current config file path, or None if not set
:setter: File existence is checked when setting parameter
* Set to ``None`` to disable the ``-config`` parameter when starting *exiftool*
* Set to ``""`` has special meaning and disables loading of the default config file. See `ExifTool documentation for -config`_ for more info.
.. note::
Currently file is checked for existence when setting. It is not checked when starting process.
:raises ExifToolRunning: If attempting to set while running (:py:attr:`running` == True)
:type: str, Path, None
.. _ExifTool documentation for -config: https://exiftool.org/exiftool_pod.html#Advanced-options
"""
return self._config_file
@config_file.setter
def config_file(self, new_config_file: Optional[Union[str, Path]]) -> None:
if self.running:
raise ExifToolRunning("Cannot set a new config_file")
if new_config_file is None:
self._config_file = None
elif new_config_file == "":
# this is VALID usage of -config parameter
# As per exiftool documentation: Loading of the default config file may be disabled by setting CFGFILE to an empty string (ie. "")
self._config_file = ""
elif not Path(new_config_file).exists():
raise FileNotFoundError("The config file could not be found")
else:
self._config_file = str(new_config_file)
if self._logger: self._logger.info(f"Property 'config_file': set to \"{self._config_file}\"")
##############################################################################################
#################################### PROPERTIES Read only ####################################
##############################################################################################
# ----------------------------------------------------------------------------------------------------------------------
@property
def running(self) -> bool:
"""
Read-only property which indicates whether the *exiftool* subprocess is running or not.
:getter: Returns current running state
.. note::
This checks to make sure the process is still alive.
If the process has died since last `running` detection, this property
will detect the state change and reset the status accordingly.
"""
if self._running:
# check if the process is actually alive
if self._process.poll() is not None:
# process died
warnings.warn("ExifTool process was previously running but died")
self._flag_running_false()
if self._logger: self._logger.warning("Property 'running': ExifTool process was previously running but died")
return self._running
# ----------------------------------------------------------------------------------------------------------------------
@property
def version(self) -> str:
"""
Read-only property which is the string returned by ``exiftool -ver``
The *-ver* command is ran once at process startup and cached.
:getter: Returns cached output of ``exiftool -ver``
:raises ExifToolNotRunning: If attempting to read while not running (:py:attr:`running` == False)
"""
if not self.running:
raise ExifToolNotRunning("Can't get ExifTool version")
return self._ver
# ----------------------------------------------------------------------------------------------------------------------
@property
def last_stdout(self) -> Optional[Union[str, bytes]]:
"""
``STDOUT`` for most recent result from execute()
.. note::
The return type can be either str or bytes.
If the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``. Otherwise this will be ``str``.
.. note::
This property can be read at any time, and is not dependent on running state of ExifTool.
It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow
for executing a command and terminating, but still having the result available.
"""
return self._last_stdout
# ----------------------------------------------------------------------------------------------------------------------
@property
def last_stderr(self) -> Optional[Union[str, bytes]]:
"""
``STDERR`` for most recent result from execute()
.. note::
The return type can be either ``str`` or ``bytes``.
If the most recent call to execute() ``raw_bytes=True``, then this will return ``bytes``. Otherwise this will be ``str``.
.. note::
This property can be read at any time, and is not dependent on running state of ExifTool.
It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow
for executing a command and terminating, but still having the result available.
"""
return self._last_stderr
# ----------------------------------------------------------------------------------------------------------------------
@property
def last_status(self) -> Optional[int]:
"""
``Exit Status Code`` for most recent result from execute()
.. note::
This property can be read at any time, and is not dependent on running state of ExifTool.
It is INTENTIONALLY *NOT* CLEARED on exiftool termination, to allow
for executing a command and terminating, but still having the result available.
"""
return self._last_status
###############################################################################################
#################################### PROPERTIES Write only ####################################
###############################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def _set_logger(self, new_logger) -> None:
""" set a new user-created logging.Logger object
can be set at any time to start logging.
Set to None at any time to stop logging.
"""
if new_logger is None:
self._logger = None
return
# can't check this in case someone passes a drop-in replacement, like loguru, which isn't type logging.Logger
#elif not isinstance(new_logger, logging.Logger):
# raise TypeError("logger needs to be of type logging.Logger")
# do some basic checks on methods available in the "logger" provided
check = True
try:
# ExifTool will probably use all of these logging method calls at some point
# check all these are callable methods
check = callable(new_logger.info) and \
callable(new_logger.warning) and \
callable(new_logger.error) and \
callable(new_logger.critical) and \
callable(new_logger.exception)
except AttributeError:
check = False
if not check:
raise TypeError("logger needs to implement methods (info,warning,error,critical,exception)")
self._logger = new_logger
# have to run this at the class level to create a special write-only property
# https://stackoverflow.com/questions/17576009/python-class-property-use-setter-but-evade-getter
# https://docs.python.org/3/howto/descriptor.html#properties
# can have it named same or different
logger = property(fset=_set_logger, doc="""Write-only property to set the class of logging.Logger""")
"""
Write-only property to set the class of logging.Logger
If this is set, then status messages will log out to the given class.
.. note::
This can be set and unset (set to ``None``) at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not.
:setter: Specify an object to log to. The class is not checked, but validation is done to ensure the object has callable methods ``info``, ``warning``, ``error``, ``critical``, ``exception``.
:raises AttributeError: If object does not contain one or more of the required methods.
:raises TypeError: If object contains those attributes, but one or more are non-callable methods.
:type: Object
"""
#########################################################################################
##################################### SETTER METHODS ####################################
#########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def set_json_loads(self, json_loads, **kwargs) -> None:
"""
**Advanced**: Override default built-in ``json.loads()`` method. The method is only used once in :py:meth:`execute_json`
This allows using a different json string parser.
(Alternate json libraries typically provide faster speed than the
built-in implementation, more supported features, and/or different behavior.)
Examples of json libraries: `orjson`_, `rapidjson`_, `ujson`_, ...
.. note::
This method is designed to be called the same way you would expect to call the provided ``json_loads`` method.
Include any ``kwargs`` you would in the call.
For example, to pass additional arguments to ``json.loads()``: ``set_json_loads(json.loads, parse_float=str)``
.. note::
This can be set at any time, regardless of whether the subprocess is running (:py:attr:`running` == True) or not.
.. warning::
This setter does not check whether the method provided actually parses json. Undefined behavior or crashes may occur if used incorrectly
This is **advanced configuration** for specific use cases only.
For an example use case, see the :ref:`FAQ `
:param json_loads: A callable method to replace built-in ``json.loads`` used in :py:meth:`execute_json`
:type json_loads: callable
:param kwargs: Parameters passed to the ``json_loads`` method call
:raises TypeError: If ``json_loads`` is not callable
.. _orjson: https://pypi.org/project/orjson/
.. _rapidjson: https://pypi.org/project/python-rapidjson/
.. _ujson: https://pypi.org/project/ujson/
"""
if not callable(json_loads):
# not a callable method
raise TypeError
self._json_loads = json_loads
self._json_loads_kwargs = kwargs
#########################################################################################
#################################### PROCESS CONTROL ####################################
#########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def run(self) -> None:
"""Start an *exiftool* subprocess in batch mode.
This method will issue a ``UserWarning`` if the subprocess is
already running (:py:attr:`running` == True). The process is started with :py:attr:`common_args` as common arguments,
which are automatically included in every command you run with :py:meth:`execute()`.
You can override these default arguments with the
``common_args`` parameter in the constructor or setting :py:attr:`common_args` before caaling :py:meth:`run()`.
.. note::
If you have another executable named *exiftool* which isn't Phil Harvey's ExifTool, then you're shooting yourself in the foot as there's no error checking for that
:raises FileNotFoundError: If *exiftool* is no longer found. Re-raised from subprocess.Popen()
:raises OSError: Re-raised from subprocess.Popen()
:raises ValueError: Re-raised from subprocess.Popen()
:raises subproccess.CalledProcessError: Re-raised from subprocess.Popen()
:raises RuntimeError: Popen() launched process but it died right away
:raises ExifToolVersionError: :py:attr:`exiftool.constants.EXIFTOOL_MINIMUM_VERSION` not met. ExifTool process will be automatically terminated.
"""
if self.running:
warnings.warn("ExifTool already running; doing nothing.", UserWarning)
return
# first the executable ...
# TODO should we check the executable for existence here?
proc_args = [self._executable, ]
# If working with a config file, it must be the first argument after the executable per: https://exiftool.org/config.html
if self._config_file is not None:
# must check explicitly for None, as "" is valid
# TODO check that the config file exists here?
proc_args.extend(["-config", self._config_file])
# this is the required stuff for the stay_open that makes pyexiftool so great!
proc_args.extend(["-stay_open", "True", "-@", "-"])
# only if there are any common_args. [] and None are skipped equally with this
if self._common_args:
proc_args.append("-common_args") # add this param only if there are common_args
proc_args.extend(self._common_args) # add the common arguments
# ---- set platform-specific kwargs for Popen ----
kwargs: dict = {}
if constants.PLATFORM_WINDOWS:
# TODO: I don't think this code actually does anything ... I've never seen a console pop up on Windows
# Perhaps need to specify subprocess.STARTF_USESHOWWINDOW to actually have any console pop up?
# https://docs.python.org/3/library/subprocess.html#windows-popen-helpers
startup_info = subprocess.STARTUPINFO()
if not self._win_shell:
# Adding enum 11 (SW_FORCEMINIMIZE in win32api speak) will
# keep it from throwing up a DOS shell when it launches.
startup_info.dwFlags |= constants.SW_FORCEMINIMIZE
kwargs["startupinfo"] = startup_info
else: # pytest-cov:windows: no cover
# assume it's linux
kwargs["preexec_fn"] = _set_pdeathsig(signal.SIGTERM)
# Warning: The preexec_fn parameter is not safe to use in the presence of threads in your application.
# https://docs.python.org/3/library/subprocess.html#subprocess.Popen
try:
# NOTE: the encoding= parameter was removed from the Popen() call to support
# using bytes in the actual communication with exiftool process.
# Due to the way the code is written, ExifTool only uses stdin.write which would need to be in bytes.
# The reading is _NOT_ using subprocess.communicate(). This class reads raw bytes using os.read()
# Therefore, by switching off the encoding= in Popen(), we can support both bytes and str at the
# same time. (This change was to support https://github.com/sylikc/pyexiftool/issues/47)
# unify both platform calls into one subprocess.Popen call
self._process = subprocess.Popen(
proc_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
except FileNotFoundError:
raise
except OSError:
raise
except ValueError:
raise
except subprocess.CalledProcessError:
raise
# TODO print out more useful error messages to these different errors above
# check error above before saying it's running
if self._process.poll() is not None:
# the Popen launched, then process terminated
self._process = None # unset it as it's now terminated
raise RuntimeError("exiftool did not execute successfully")
# have to set this before doing the checks below, or else execute() will fail
self._running = True
# get ExifTool version here and any Exiftool metadata
# this can also verify that it is really ExifTool we ran, not some other random process
try:
# apparently because .execute() has code that already depends on v12.15+ functionality,
# _parse_ver() will throw a ValueError immediately with:
# ValueError: invalid literal for int() with base 10: '${status}'
self._ver = self._parse_ver()
except ValueError:
# trap the error and return it as a minimum version problem
self.terminate()
raise ExifToolVersionError(f"Error retrieving Exiftool info. Is your Exiftool version ('exiftool -ver') >= required version ('{constants.EXIFTOOL_MINIMUM_VERSION}')?")
if self._logger: self._logger.info(f"Method 'run': Exiftool version '{self._ver}' (pid {self._process.pid}) launched with args '{proc_args}'")
# currently not needed... if it passes -ver check, the rest is OK
# may use in the future again if another version feature is needed but the -ver check passes
"""
# check that the minimum required version is met, if not, terminate...
# if you run against a version which isn't supported, strange errors come up during execute()
if not self._exiftool_version_check():
self.terminate()
if self._logger: self._logger.error(f"Method 'run': Exiftool version '{self._ver}' did not meet the required minimum version '{constants.EXIFTOOL_MINIMUM_VERSION}'")
raise ExifToolVersionError(f"exiftool version '{self._ver}' < required '{constants.EXIFTOOL_MINIMUM_VERSION}'")
"""
# ----------------------------------------------------------------------------------------------------------------------
def terminate(self, timeout: int = 30, _del: bool = False) -> None:
"""Terminate the *exiftool* subprocess.
If the subprocess isn't running, this method will throw a warning, and do nothing.
.. note::
There is a bug in CPython 3.8+ on Windows where terminate() does not work during ``__del__()``
See CPython issue `starting a thread in __del__ hangs at interpreter shutdown`_ for more info.
.. _starting a thread in __del__ hangs at interpreter shutdown: https://github.com/python/cpython/issues/87950
"""
if not self.running:
warnings.warn("ExifTool not running; doing nothing.", UserWarning)
return
if _del and constants.PLATFORM_WINDOWS:
# don't cleanly exit on windows, during __del__ as it'll freeze at communicate()
self._process.kill()
#print("before comm", self._process.poll(), self._process)
self._process.poll()
try:
# TODO freezes here on windows if subprocess zombie remains
outs, errs = self._process.communicate() # have to cleanup the process or else .poll() will return None
#print("after comm")
# TODO a bug filed with Python, or user error... this doesn't seem to work at all ... .communicate() still hangs
# https://bugs.python.org/issue43784 , https://github.com/python/cpython/issues/87950... Windows-specific issue affecting Python 3.8-3.10 (as of this time)
except RuntimeError:
# Python 3.12 throws a runtime error -- see https://github.com/python/cpython/pull/104826
# RuntimeError: can't create new thread at interpreter shutdown
pass
else:
try:
"""
On Windows, running this after __del__ freezes at communicate(), regardless of timeout
see the bug filed above for details
On Linux, this runs as is, and the process terminates properly
"""
try:
self._process.communicate(input=b"-stay_open\nFalse\n", timeout=timeout) # this is a constant sequence specified by PH's exiftool
except RuntimeError:
# Python 3.12 throws a runtime error -- see https://github.com/python/cpython/pull/104826
# RuntimeError: can't create new thread at interpreter shutdown
pass
self._process.kill()
except subprocess.TimeoutExpired: # this is new in Python 3.3 (for python 2.x, use the PyPI subprocess32 module)
self._process.kill()
outs, errs = self._process.communicate()
# err handling code from https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
self._flag_running_false()
# TODO log / return exit status from exiftool?
if self._logger: self._logger.info("Method 'terminate': Exiftool terminated successfully.")
##################################################################################
#################################### EXECUTE* ####################################
##################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def execute(self, *params: Union[str, bytes], raw_bytes: bool = False) -> Union[str, bytes]:
"""Execute the given batch of parameters with *exiftool*.
This method accepts any number of parameters and sends them to
the attached ``exiftool`` subprocess. The process must be
running, otherwise :py:exc:`exiftool.exceptions.ExifToolNotRunning` is raised. The final
``-execute`` necessary to actually run the batch is appended
automatically; see the documentation of :py:meth:`run()` for
the common options. The ``exiftool`` output is read up to the
end-of-output sentinel and returned as a ``str`` decoded
based on the currently set :py:attr:`encoding`,
excluding the sentinel.
The parameters must be of type ``str`` or ``bytes``.
``str`` parameters are encoded to bytes automatically using the :py:attr:`encoding` property.
For filenames, this should be the system's filesystem encoding.
``bytes`` parameters are untouched and passed directly to ``exiftool``.
.. note::
This is the core method to interface with the ``exiftool`` subprocess.
No processing is done on the input or output.
:param params: One or more parameters to send to the ``exiftool`` subprocess.
Typically passed in via `Unpacking Argument Lists`_
.. note::
The parameters to this function must be type ``str`` or ``bytes``.
:type params: one or more string/bytes parameters
:param raw_bytes: If True, returns bytes. Default behavior returns a str
:return:
* STDOUT is returned by the method call, and is also set in :py:attr:`last_stdout`
* STDERR is set in :py:attr:`last_stderr`
* Exit Status of the command is set in :py:attr:`last_status`
:raises ExifToolNotRunning: If attempting to execute when not running (:py:attr:`running` == False)
:raises ExifToolVersionError: If unexpected text was returned from the command while parsing out the sentinels
:raises UnicodeDecodeError: If the :py:attr:`encoding` is not specified properly, it may be possible for ``.decode()`` method to raise this error
:raises TypeError: If ``params`` argument is not ``str`` or ``bytes``
.. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
"""
if not self.running:
raise ExifToolNotRunning("Cannot execute()")
# ---------- build the special params to execute ----------
# there's a special usage of execute/ready specified in the manual which make almost ensure we are receiving the right signal back
# from exiftool man pages: When this number is added, -q no longer suppresses the "{ready}"
signal_num = random.randint(100000, 999999) # arbitrary create a 6 digit number (keep it down to save memory maybe)
# constant special sequences when running -stay_open mode
seq_execute = f"-execute{signal_num}\n" # the default string is b"-execute\n"
seq_ready = f"{{ready{signal_num}}}" # the default string is b"{ready}"
# these are special sequences to help with synchronization. It will print specific text to STDERR before and after processing
#SEQ_STDERR_PRE_FMT = "pre{}" # can have a PRE sequence too but we don't need it for syncing
seq_err_post = f"post{signal_num}" # default there isn't any string
SEQ_ERR_STATUS_DELIM = "=" # this can be configured to be one or more chacters... the code below will accomodate for longer sequences: len() >= 1
seq_err_status = "${status}" # a special sequence, ${status} returns EXIT STATUS as per exiftool documentation - only supported on exiftool v12.10+
# ---------- build the params list and encode the params to bytes, if necessary ----------
cmd_params: List[bytes] = []
# this is necessary as the encoding parameter of Popen() is not specified. We manually encode as per the .encoding() parameter
for p in params:
# we use isinstance() over type() not only for subclass, but
# according to https://switowski.com/blog/type-vs-isinstance
# isinstance() is 40% faster than type()
if isinstance(p, bytes):
# no conversion needed, pass in raw (caller has already encoded)
cmd_params.append(p)
elif isinstance(p, str):
# conversion needed, encode based on specified encoding
cmd_params.append(p.encode(self._encoding))
else:
# technically at this point we could support any object and call str()
# but leave this up to an extended class like ExifToolHelper()
raise TypeError(f"ERROR: Parameter was not bytes/str: {type(p)} => {p}")
# f-strings are faster than concatentation of multiple strings -- https://stackoverflow.com/questions/59180574/string-concatenation-with-vs-f-string
cmd_params.extend(
(b"-echo4",
f"{SEQ_ERR_STATUS_DELIM}{seq_err_status}{SEQ_ERR_STATUS_DELIM}{seq_err_post}".encode(self._encoding),
seq_execute.encode(self._encoding))
)
cmd_bytes = b"\n".join(cmd_params)
# ---------- write to the pipe connected with exiftool process ----------
self._process.stdin.write(cmd_bytes)
self._process.stdin.flush()
if self._logger: self._logger.info("Method 'execute': Command sent = {}".format(cmd_params[:-1])) # logs without the -execute (it would confuse people to include that)
# ---------- read output from exiftool process until special sequences reached ----------
# NOTE:
#
# while subprocess recommends: "Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process."
#
# this raw reading is used instead of Popen.communicate() due to the note:
# https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
#
# "The data read is buffered in memory, so do not use this method if the data size is large or unlimited."
#
# The data that comes back from exiftool falls into this, and so unbuffered reads are done with os.read()
fdout = self._process.stdout.fileno()
raw_stdout = _read_fd_endswith(fdout, seq_ready.encode(self._encoding), self._block_size)
# when it's ready, we can safely read all of stderr out, as the command is already done
fderr = self._process.stderr.fileno()
raw_stderr = _read_fd_endswith(fderr, seq_err_post.encode(self._encoding), self._block_size)
if not raw_bytes:
# decode if not returning bytes
raw_stdout = raw_stdout.decode(self._encoding)
raw_stderr = raw_stderr.decode(self._encoding)
# ---------- parse output ----------
# save the outputs to some variables first
cmd_stdout = raw_stdout.strip()[:-len(seq_ready)]
cmd_stderr = raw_stderr.strip()[:-len(seq_err_post)] # save it in case the error below happens and output can be checked easily
# if raw_bytes is True, the check has to become bytes rather than str
err_status_delim = SEQ_ERR_STATUS_DELIM if not raw_bytes else SEQ_ERR_STATUS_DELIM.encode(self._encoding)
# sanity check the status code from the stderr output
delim_len = len(err_status_delim)
if cmd_stderr[-delim_len:] != err_status_delim:
# exiftool is expected to dump out the status code within the delims... if it doesn't, the class doesn't match expected exiftool output for current version
raise ExifToolVersionError(f"Exiftool expected to return status on stderr, but got unexpected character: {cmd_stderr[-delim_len:]} != {err_status_delim}")
# look for the previous delim (we could use regex here to do all this in one step, but it's probably overkill, and could slow down the code significantly)
# the other simplification that can be done is that, as of this writing: Exiftool is expected to only return 0, 1, or 2 as per documentation
# you could just lop the last 3 characters off... but if the return status changes in the future, then this code would break
err_delim_1 = cmd_stderr.rfind(err_status_delim, 0, -delim_len)
cmd_status = cmd_stderr[err_delim_1 + delim_len : -delim_len]
# ---------- save the output to class vars for later retrieval ----------
# lop off the actual status code from stderr
self._last_stderr = cmd_stderr[:err_delim_1]
self._last_stdout = cmd_stdout
# can check .isnumeric() here, but best just to duck-type cast it
self._last_status = int(cmd_status)
if self._logger:
self._logger.debug(f"{self.__class__.__name__}.execute: IN params = {params}")
self._logger.debug(f"{self.__class__.__name__}.execute: OUT stdout = \"{self._last_stdout}\"")
self._logger.debug(f"{self.__class__.__name__}.execute: OUT stderr = \"{self._last_stderr}\"")
self._logger.debug(f"{self.__class__.__name__}.execute: OUT status = {self._last_status}")
# the standard return: just stdout
# if you need other output, retrieve from properties
return self._last_stdout
# ----------------------------------------------------------------------------------------------------------------------
def execute_json(self, *params: Union[str, bytes]) -> List:
"""Execute the given batch of parameters and parse the JSON output.
This method is similar to :py:meth:`execute()`. It
automatically adds the parameter ``-j`` to request JSON output
from ``exiftool`` and parses the output.
The return value is
a list of dictionaries, mapping tag names to the corresponding
values. All keys are strings.
The values can have multiple types. Each dictionary contains the
name of the file it corresponds to in the key ``"SourceFile"``.
.. note::
By default, the tag names include the group name in the format : (if using the ``-G`` option).
You can adjust the output structure with various *exiftool* options.
.. warning::
This method does not verify the exit status code returned by *exiftool*. That is left up to the caller.
This will mimic exiftool's default method of operation "continue on error" and "best attempt" to complete commands given.
If you want automated error checking, use :py:class:`exiftool.ExifToolHelper`
:param params: One or more parameters to send to the ``exiftool`` subprocess.
Typically passed in via `Unpacking Argument Lists`_
.. note::
The parameters to this function must be type ``str`` or ``bytes``.
:type params: one or more string/bytes parameters
:return: Valid JSON parsed into a Python list of dicts
:raises ExifToolOutputEmptyError: If *exiftool* did not return any STDOUT
.. note::
This is not necessarily an *exiftool* error, but rather a programmer error.
For example, setting tags can cause this behavior.
If you are executing a command and expect no output, use :py:meth:`execute()` instead.
:raises ExifToolJSONInvalidError: If *exiftool* returned STDOUT which is invalid JSON.
.. note::
This is not necessarily an *exiftool* error, but rather a programmer error.
For example, ``-w`` can cause this behavior.
If you are executing a command and expect non-JSON output, use :py:meth:`execute()` instead.
.. _Unpacking Argument Lists: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
"""
result = self.execute("-j", *params) # stdout
# NOTE: I have decided NOT to check status code
# There are quite a few use cases where it's desirable to have continue-on-error behavior,
# as that is exiftool's default mode of operation. exiftool normally just does what it can
# and tells you that it did all this and that, but some files didn't process. In this case
# exit code is non-zero, but exiftool did SOMETHING. I leave it up to the caller to figure
# out what was done or not done.
if len(result) == 0:
# the output from execute() can be empty under many relatively ambiguous situations
# * command has no files it worked on
# * a file specified or files does not exist
# * some other type of error
# * a command that does not return anything (like metadata manipulation/setting tags)
#
# There's no easy way to check which params are files, or else we have to reproduce the parser exiftool does (so it's hard to detect to raise a FileNotFoundError)
# Returning [] could be ambiguous if Exiftool changes the returned JSON structure in the future
# Returning None was preferred, because it's the safest as it clearly indicates that nothing came back from execute(), but it means execute_json() doesn't always return JSON
# Raising an error is the current solution, as that clearly indicates that you used execute_json() expecting output, but got nothing
raise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params)
try:
parsed = self._json_loads(result, **self._json_loads_kwargs)
except ValueError as e:
# most known JSON libraries return ValueError or a subclass.
# built-in json.JSONDecodeError is a subclass of ValueError -- https://docs.python.org/3/library/json.html#json.JSONDecodeError
# if `-w` flag is specified in common_args or params, stdout will not be JSON parseable
#
# which will return something like:
# x image files read
# x output files created
# the user is expected to know this ahead of time, and if -w exists in common_args or as a param, this error will be thrown
# explicit chaining https://www.python.org/dev/peps/pep-3134/
raise ExifToolJSONInvalidError(self._last_status, self._last_stdout, self._last_stderr, params) from e
return parsed
#########################################################################################
#################################### PRIVATE METHODS ####################################
#########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def _flag_running_false(self) -> None:
""" private method that resets the "running" state
It used to be that there was only self._running to unset, but now it's a trio of variables
This method makes it less likely a maintainer will leave off a variable if other ones are added in the future
"""
self._process = None # don't delete, just leave as None
self._ver = None # unset the version
self._running = False
# as an FYI, as per the last_* properties, they are intentionally not cleared when process closes
# ----------------------------------------------------------------------------------------------------------------------
def _parse_ver(self):
""" private method to run exiftool -ver
and parse out the information
"""
if not self.running:
raise ExifToolNotRunning("Cannot get version")
# -ver is just the version
# -v gives you more info (perl version, platform, libraries) but isn't helpful for this library
# -v2 gives you even more, but it's less useful at that point
return self.execute("-ver").strip()
# ----------------------------------------------------------------------------------------------------------------------
"""
def _exiftool_version_check(self) -> bool:
"" " private method to check the minimum required version of ExifTool
returns false if the version check fails
returns true if it's OK
"" "
# parse (major, minor) with integers... so far Exiftool versions are all ##.## with no exception
# this isn't entirely tested... possibly a version with more "." or something might break this parsing
arr: List = self._ver.split(".", 1) # split to (major).(whatever)
version_nums: List = []
try:
for v in arr:
res.append(int(v))
except ValueError:
raise ValueError(f"Error parsing ExifTool version for version check: '{self._ver}'")
if len(version_nums) != 2:
raise ValueError(f"Expected Major.Minor len()==2, got: {version_nums}")
curr_major, curr_minor = version_nums
# same logic above except on one line
req_major, req_minor = [int(x) for x in constants.EXIFTOOL_MINIMUM_VERSION.split(".", 1)]
if curr_major > req_major:
# major version is bigger
return True
elif curr_major < req_major:
# major version is smaller
return False
elif curr_minor >= req_minor:
# major version is equal
# current minor is equal or better
return True
else:
# anything else is False
return False
"""
# ----------------------------------------------------------------------------------------------------------------------
================================================
FILE: exiftool/experimental.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
This submodule contains the ``ExifToolAlpha`` class, which extends the ``ExifToolHelper`` class with experimental functionality.
.. note::
:py:class:`exiftool.helper.ExifToolAlpha` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolAlpha`
"""
from pathlib import Path
from .helper import ExifToolHelper
try: # Py3k compatibility
basestring
except NameError:
basestring = (bytes, str)
# ======================================================================================================================
#def atexit_handler
# constants related to keywords manipulations
KW_TAGNAME = "IPTC:Keywords"
KW_REPLACE, KW_ADD, KW_REMOVE = range(3)
# ======================================================================================================================
#string helper
def strip_nl(s):
return ' '.join(s.splitlines())
# ======================================================================================================================
# Error checking function
# very rudimentary checking
# Note: They are quite fragile, because this just parses the output text from exiftool
def check_ok(result):
"""Evaluates the output from a exiftool write operation (e.g. `set_tags`)
The argument is the result from the execute method.
The result is True or False.
"""
return not result is None and (not "due to errors" in result)
# ======================================================================================================================
def format_error(result):
"""Evaluates the output from a exiftool write operation (e.g. `set_tags`)
The argument is the result from the execute method.
The result is a human readable one-line string.
"""
if check_ok(result):
return f'exiftool probably finished properly. ("{strip_nl(result)}")'
else:
if result is None:
return "exiftool operation can't be evaluated: No result given"
else:
return f'exiftool finished with error: "{strip_nl(result)}"'
# ======================================================================================================================
class ExifToolAlpha(ExifToolHelper):
"""
This class is for the "experimental" functionality. In the grand scheme of things, this class
contains "not well tested" functionality, methods that are less used, or methods with niche use cases.
In some methods, edge cases on some of these methods may produce unexpected or ambiguous results.
However, if there is increased demand, or robustness improves, functionality may merge into
:py:class:`exiftool.ExifToolHelper` class.
The starting point of this class was to remove all the "less used" functionality that was merged in
on some arbitrary pull requests to the original v0.2 PyExifTool repository. This alpha-quality code is brittle and contains
a lot of "hacks" for a niche set of use cases. As such, it may be buggy and it shouldn't crowd the core functionality
of the :py:class:`exiftool.ExifTool` class or the stable extended functionality of the :py:class:`exiftool.ExifToolHelper` class
with unneeded bloat.
The class heirarchy: ExifTool -> ExifToolHelper -> ExifToolAlpha
* ExifTool - stable base class with CORE functionality
* ExifToolHelper - user friendly class that extends the base class with general functionality not found in the core
* ExifToolAlpha - alpha-quality code which extends the ExifToolHelper to add functionality that is niche, brittle, or not well tested
Because of this heirarchy, you could always use/extend the :py:class:`exiftool.ExifToolAlpha` class to have all functionality,
or at your discretion, use one of the more stable classes above.
Please issue PR to this class to add functionality, even if not tested well. This class is for experimental code after all!
"""
# ----------------------------------------------------------------------------------------------------------------------
# i'm not sure if the verification works, but related to pull request (#11)
def execute_json_wrapper(self, filenames, params=None, retry_on_error=True):
# make sure the argument is a list and not a single string
# which would lead to strange errors
if isinstance(filenames, basestring):
raise TypeError("The argument 'filenames' must be an iterable of strings")
execute_params = []
if params:
execute_params.extend(params)
execute_params.extend(filenames)
result = self.execute_json(execute_params)
if result:
try:
ExifToolAlpha._check_result_filelist(filenames, result)
except IOError as error:
# Restart the exiftool child process in these cases since something is going wrong
self.terminate()
self.run()
if retry_on_error:
result = self.execute_json_filenames(filenames, params, retry_on_error=False)
else:
raise error
else:
# Reasons for exiftool to provide an empty result, could be e.g. file not found, etc.
# What should we do in these cases? We don't have any information what went wrong, therefore
# we just return empty dictionaries.
result = [{} for _ in filenames]
return result
# ----------------------------------------------------------------------------------------------------------------------
# allows adding additional checks (#11)
def get_metadata_batch_wrapper(self, filenames, params=None):
return self.execute_json_wrapper(filenames=filenames, params=params)
# ----------------------------------------------------------------------------------------------------------------------
# (#11)
def get_metadata_wrapper(self, filename, params=None):
return self.execute_json_wrapper(filenames=[filename], params=params)[0]
# ----------------------------------------------------------------------------------------------------------------------
# (#11)
def get_tags_batch_wrapper(self, tags, filenames, params=None):
params = (params if params else []) + ["-" + t for t in tags]
return self.execute_json_wrapper(filenames=filenames, params=params)
# ----------------------------------------------------------------------------------------------------------------------
# (#11)
def get_tags_wrapper(self, tags, filename, params=None):
return self.get_tags_batch_wrapper(tags, [filename], params=params)[0]
# ----------------------------------------------------------------------------------------------------------------------
# (#11)
def get_tag_batch_wrapper(self, tag, filenames, params=None):
data = self.get_tags_batch_wrapper([tag], filenames, params=params)
result = []
for d in data:
d.pop("SourceFile")
result.append(next(iter(d.values()), None))
return result
# ----------------------------------------------------------------------------------------------------------------------
# this was a method with good intentions by the original author, but returns some inconsistent results in some cases
# for example, if you passed in a single tag, or a group name, it would return the first tag back instead of the whole group
# try calling get_tag_batch("*.mp4", "QuickTime") or "QuickTime:all" ... the expected results is a dictionary but a single tag is returned
def get_tag_batch(self, filenames, tag):
"""Extract a single tag from the given files.
The first argument is a single tag name, as usual in the
format :.
The second argument is an iterable of file names.
The return value is a list of tag values or ``None`` for
non-existent tags, in the same order as ``filenames``.
"""
data = self.get_tags(filenames, [tag])
result = []
for d in data:
d.pop("SourceFile")
result.append(next(iter(d.values()), None))
return result
# ----------------------------------------------------------------------------------------------------------------------
# (#11)
def get_tag_wrapper(self, tag, filename, params=None):
return self.get_tag_batch_wrapper(tag, [filename], params=params)[0]
# ----------------------------------------------------------------------------------------------------------------------
def get_tag(self, filename, tag):
"""
Extract a single tag from a single file.
The return value is the value of the specified tag, or
``None`` if this tag was not found in the file.
Does existence checks
"""
#return self.get_tag_batch([filename], tag)[0]
p = Path(filename)
if not p.exists():
raise FileNotFoundError
data = self.get_tags(p, tag)
if len(data) > 1:
raise RuntimeError("one file requested but multiple returned?")
d = data[0]
d.pop("SourceFile")
if len(d.values()) > 1:
raise RuntimeError("multiple tag values returned, invalid use case")
return next(iter(d.values()), None)
# ----------------------------------------------------------------------------------------------------------------------
def copy_tags(self, from_filename, to_filename):
"""Copy all tags from one file to another."""
params = ["-overwrite_original", "-TagsFromFile", str(from_filename), str(to_filename)]
self.execute(*params)
# ----------------------------------------------------------------------------------------------------------------------
def set_keywords_batch(self, files, mode, keywords):
"""Modifies the keywords tag for the given files.
The first argument is the operation mode:
* KW_REPLACE: Replace (i.e. set) the full keywords tag with `keywords`.
* KW_ADD: Add `keywords` to the keywords tag.
If a keyword is present, just keep it.
* KW_REMOVE: Remove `keywords` from the keywords tag.
If a keyword wasn't present, just leave it.
The second argument is an iterable of key words.
The third argument is an iterable of file names.
The format of the return value is the same as for
:py:meth:`execute()`.
It can be passed into `check_ok()` and `format_error()`.
"""
# Explicitly ruling out strings here because passing in a
# string would lead to strange and hard-to-find errors
if isinstance(keywords, basestring):
raise TypeError("The argument 'keywords' must be "
"an iterable of strings")
# allow the files argument to be a str, and process it into a list of str
filenames = self.__class__._parse_arg_files(files)
params = []
kw_operation = {KW_REPLACE: "-%s=%s",
KW_ADD: "-%s+=%s",
KW_REMOVE: "-%s-=%s"}[mode]
kw_params = [kw_operation % (KW_TAGNAME, w) for w in keywords]
params.extend(kw_params)
params.extend(filenames)
if self._logger: self._logger.debug(params)
return self.execute(*params)
# ----------------------------------------------------------------------------------------------------------------------
def set_keywords(self, filename, mode, keywords):
"""Modifies the keywords tag for the given file.
This is a convenience function derived from `set_keywords_batch()`.
Only difference is that it takes as last argument only one file name
as a string.
"""
return self.set_keywords_batch([filename], mode, keywords)
# ----------------------------------------------------------------------------------------------------------------------
@staticmethod
def _check_result_filelist(file_paths, result):
"""
Checks if the given file paths matches the 'SourceFile' entries in the result returned by
exiftool. This is done to find possible mix ups in the streamed responses.
"""
# do some sanity checks on the results to make sure nothing was mixed up during reading from stdout
if len(result) != len(file_paths):
raise IOError(f"exiftool returned {len(result)} results, but expected was {len(file_paths)}")
for i in range(len(file_paths)):
returned_source_file = result[i].get('SourceFile')
requested_file = file_paths[i]
if returned_source_file != requested_file:
raise IOError(f"exiftool returned data for file {returned_source_file}, but expected was {requested_file}")
# ----------------------------------------------------------------------------------------------------------------------
================================================
FILE: exiftool/helper.py
================================================
# -*- coding: utf-8 -*-
#
# This file is part of PyExifTool.
#
# PyExifTool
#
# Copyright 2019-2023 Kevin M (sylikc)
# Copyright 2012-2014 Sven Marnach
#
# Community contributors are listed in the CHANGELOG.md for the PRs
#
# PyExifTool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the licence, or
# (at your option) any later version, or the BSD licence.
#
# PyExifTool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING.GPL or COPYING.BSD for more details.
"""
This submodule contains the ``ExifToolHelper`` class, which makes the core ``ExifTool`` class easier, and safer to use.
.. note::
:py:class:`exiftool.helper.ExifToolHelper` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolHelper`
"""
import re
from .exiftool import ExifTool
from .exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError, ExifToolTagNameError
# basestring makes no sense in Python 3, so renamed tuple to this const
TUPLE_STR_BYTES: tuple = (str, bytes,)
from typing import Any, Union, Optional, List, Dict
# ======================================================================================================================
def _is_iterable(in_param: Any, ignore_str_bytes: bool = False) -> bool:
"""
Checks if this item is iterable, instead of using isinstance(list), anything iterable can be ok
.. note::
STRINGS ARE CONSIDERED ITERABLE by Python
if you need to consider a code path for strings first, check that before checking if a parameter is iterable via this function
or specify ``ignore_str_bytes=True``
:param in_param: Something to check if iterable or not
:param ignore_str_bytes: str/bytes are iterable. But usually we don't want to check that. set ``ignore_str_bytes`` to ``True`` to ignore strings on check
"""
if ignore_str_bytes and isinstance(in_param, TUPLE_STR_BYTES):
return False
# a different type of test of iterability, instead of using isinstance(list)
# https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable
try:
iterator = iter(in_param)
except TypeError:
return False
return True
# ======================================================================================================================
class ExifToolHelper(ExifTool):
"""
This class extends the low-level :py:class:`exiftool.ExifTool` class with 'wrapper'/'helper' functionality
It keeps low-level core functionality with the base class but extends helper functions in a separate class
"""
##########################################################################################
#################################### OVERRIDE METHODS ####################################
##########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
def __init__(self, auto_start: bool = True, check_execute: bool = True, check_tag_names: bool = True, **kwargs) -> None:
"""
:param bool auto_start: Will automatically start the exiftool process on first command run, defaults to True
:param bool check_execute: Will check the exit status (return code) of all commands. This catches some invalid commands passed to exiftool subprocess, defaults to True. See :py:attr:`check_execute` for more info.
:param bool check_tag_names: Will check the tag names provided to methods which work directly with tag names. This catches unintended uses and bugs, default to True. See :py:attr:`check_tag_names` for more info.
:param kwargs: All other parameters are passed directly to the super-class constructor: :py:meth:`exiftool.ExifTool.__init__()`
"""
# call parent's constructor
super().__init__(**kwargs)
self._auto_start: bool = auto_start
self._check_execute: bool = check_execute
self._check_tag_names: bool = check_tag_names
# ----------------------------------------------------------------------------------------------------------------------
def execute(self, *params: Any, **kwargs) -> Union[str, bytes]:
"""
Override the :py:meth:`exiftool.ExifTool.execute()` method
Adds logic to auto-start if not running, if :py:attr:`auto_start` == True
Adds logic to str() any parameter which is not a str or bytes. (This allows passing in objects like Path _without_ casting before passing it in.)
:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero
"""
if self._auto_start and not self.running:
self.run()
# by default, any non-(str/bytes) would throw a TypeError from ExifTool.execute(), so they're casted to a string here
#
# duck-type any given object to string
# this was originally to support Path() but it's now generic enough to support any object that str() to something useful
#
# Thanks @jangop for the single line contribution!
str_bytes_params: Union[str, bytes] = [x if isinstance(x, TUPLE_STR_BYTES) else str(x) for x in params]
# TODO: this list copy could be expensive if the input is a very huge list. Perhaps in the future have a flag that takes the lists in verbatim without any processing?
result: Union[str, bytes] = super().execute(*str_bytes_params, **kwargs)
# imitate the subprocess.run() signature. check=True will check non-zero exit status
if self._check_execute and self._last_status:
raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, str_bytes_params)
return result
# ----------------------------------------------------------------------------------------------------------------------
def run(self) -> None:
"""
override the :py:meth:`exiftool.ExifTool.run()` method
Will not attempt to run if already running (so no warning about 'ExifTool already running' will trigger)
"""
if self.running:
return
super().run()
# ----------------------------------------------------------------------------------------------------------------------
def terminate(self, **opts) -> None:
"""
Overrides the :py:meth:`exiftool.ExifTool.terminate()` method.
Will not attempt to terminate if not running (so no warning about 'ExifTool not running' will trigger)
:param opts: passed directly to the parent call :py:meth:`exiftool.ExifTool.terminate()`
"""
if not self.running:
return
super().terminate(**opts)
########################################################################################
#################################### NEW PROPERTIES ####################################
########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
@property
def auto_start(self) -> bool:
"""
Read-only property. Gets the current setting passed into the constructor as to whether auto_start is enabled or not.
(There's really no point to having this a read-write property, but allowing a read can be helpful at runtime to detect expected behavior.)
"""
return self._auto_start
# ----------------------------------------------------------------------------------------------------------------------
@property
def check_execute(self) -> bool:
"""
Flag to enable/disable checking exit status (return code) on execute
If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolExecuteError` if a non-zero exit status is returned during :py:meth:`execute()`
.. warning::
While this property is provided to give callers an option to enable/disable error checking, it is generally **NOT** recommended to disable ``check_execute``.
**If disabled, exiftool will fail silently, and hard-to-catch bugs may arise.**
That said, there may be some use cases where continue-on-error behavior is desired. (Example: dump all exif in a directory with files which don't all have the same tags, exiftool returns exit code 1 for unknown files, but results are valid for other files with those tags)
:getter: Returns current setting
:setter: Enable or Disable the check
.. note::
This settings can be changed any time and will only affect subsequent calls
:type: bool
"""
return self._check_execute
@check_execute.setter
def check_execute(self, new_setting: bool) -> None:
self._check_execute = new_setting
# ----------------------------------------------------------------------------------------------------------------------
@property
def check_tag_names(self) -> bool:
"""
Flag to enable/disable checking of tag names
If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolTagNameError` if an invalid tag name is detected.
.. warning::
ExifToolHelper only checks the validity of the Tag **NAME** based on a simple regex pattern.
* It *does not* validate whether the tag name is actually valid on the file type(s) you're accessing.
* It *does not* validate whether the tag you passed in that "looks like" a tag is actually an option
* It does support a "#" at the end of the tag name to disable print conversion
Please refer to `ExifTool Tag Names`_ documentation for a complete list of valid tags recognized by ExifTool.
.. warning::
While this property is provided to give callers an option to enable/disable tag names checking, it is generally **NOT** recommended to disable ``check_tag_names``.
**If disabled, you could accidentally edit a file when you meant to read it.**
Example: ``get_tags("a.jpg", "tag=value")`` will call ``execute_json("-tag=value", "a.jpg")`` which will inadvertently write to a.jpg instead of reading it!
That said, if PH's exiftool changes its tag name regex and tag names are being erroneously rejected because of this flag, disabling this could be used as a workaround (more importantly, if this is happening, please `file an issue`_!).
:getter: Returns current setting
:setter: Enable or Disable the check
.. note::
This settings can be changed any time and will only affect subsequent calls
:type: bool
.. _file an issue: https://github.com/sylikc/pyexiftool/issues
.. _ExifTool Tag Names: https://exiftool.org/TagNames/
"""
return self._check_tag_names
@check_tag_names.setter
def check_tag_names(self, new_setting: bool) -> None:
self._check_tag_names = new_setting
# ----------------------------------------------------------------------------------------------------------------------
#####################################################################################
#################################### NEW METHODS ####################################
#####################################################################################
# all generic helper functions will follow a convention of
# function(files to be worked on, ... , params=)
# ----------------------------------------------------------------------------------------------------------------------
def get_metadata(self, files: Union[str, List], params: Optional[Union[str, List]] = None) -> List:
"""
Return all metadata for the given files.
.. note::
This is a convenience method.
The implementation calls :py:meth:`get_tags()` with ``tags=None``
:param files: Files parameter matches :py:meth:`get_tags()`
:param params: Optional parameters to send to *exiftool*
:type params: list or None
:return: The return value will have the format described in the documentation of :py:meth:`get_tags()`.
"""
return self.get_tags(files, None, params=params)
# ----------------------------------------------------------------------------------------------------------------------
def get_tags(self, files: Union[Any, List[Any]], tags: Optional[Union[str, List]], params: Optional[Union[str, List]] = None) -> List:
"""
Return only specified tags for the given files.
:param files: File(s) to be worked on.
* If a non-iterable is provided, it will get tags for a single item (str(non-iterable))
* If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim.
.. note::
Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`.
.. warning::
Currently, filenames are NOT checked for existence! That is left up to the caller.
.. warning::
Wildcard strings are valid and passed verbatim to exiftool.
However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing,
which may cause unexpected behavior if you're using one and comparing the result to the other.
Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info.
:type files: Any or List(Any) - see Note
:param tags: Tag(s) to read. If tags is None, or [], method will returns all tags
.. note::
The tag names may include group names, as usual in the format ``:``.
:type tags: str, list, or None
:param params: Optional parameter(s) to send to *exiftool*
:type params: Any, List[Any], or None
:return: The format of the return value is the same as for :py:meth:`exiftool.ExifTool.execute_json()`.
:raises ValueError: Invalid Parameter
:raises TypeError: Invalid Parameter
:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero
.. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2
"""
final_tags: Optional[List] = None
final_files: List = self.__class__._parse_arg_files(files)
if tags is None:
# all tags
final_tags = []
elif isinstance(tags, TUPLE_STR_BYTES):
final_tags = [tags]
elif _is_iterable(tags):
final_tags = tags
else:
raise TypeError(f"{self.__class__.__name__}.get_tags: argument 'tags' must be a str/bytes or a list")
if self._check_tag_names:
# run check if enabled
self.__class__._check_tag_list(final_tags)
exec_params: List = []
# we extend an empty list to avoid modifying any referenced inputs
if params:
if _is_iterable(params, ignore_str_bytes=True):
exec_params.extend(params)
else:
exec_params.append(params)
# tags is always a list by this point. It will always be iterable... don't have to check for None
exec_params.extend([f"-{t}" for t in final_tags])
exec_params.extend(final_files)
try:
ret = self.execute_json(*exec_params)
except ExifToolOutputEmptyError:
raise
#raise RuntimeError(f"{self.__class__.__name__}.get_tags: exiftool returned no data")
except ExifToolJSONInvalidError:
raise
except ExifToolExecuteError:
# if last_status is <> 0, raise an error that one or more files failed?
raise
return ret
# ----------------------------------------------------------------------------------------------------------------------
def set_tags(self, files: Union[Any, List[Any]], tags: Dict, params: Optional[Union[str, List]] = None):
"""
Writes the values of the specified tags for the given file(s).
:param files: File(s) to be worked on.
* If a non-iterable is provided, it will get tags for a single item (str(non-iterable))
* If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim.
.. note::
Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`.
.. warning::
Currently, filenames are NOT checked for existence! That is left up to the caller.
.. warning::
Wildcard strings are valid and passed verbatim to exiftool.
However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing,
which may cause unexpected behavior if you're using one and comparing the result to the other.
Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info.
:type files: Any or List(Any) - see Note
:param tags: Tag(s) to write.
Dictionary keys = tags, values = tag values (str or list)
* If a value is a str, will set key=value
* If a value is a list, will iterate over list and set each individual value to the same tag (
.. note::
The tag names may include group names, as usual in the format ``:``.
.. note::
Value of the dict can be a list, in which case, the tag will be passed with each item in the list, in the order given
This allows setting things like ``-Keywords=a -Keywords=b -Keywords=c`` by passing in ``tags={"Keywords": ['a', 'b', 'c']}``
:type tags: dict
:param params: Optional parameter(s) to send to *exiftool*
:type params: str, list, or None
:return: The format of the return value is the same as for :py:meth:`execute()`.
:raises ValueError: Invalid Parameter
:raises TypeError: Invalid Parameter
:raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero
.. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2
"""
final_files: List = self.__class__._parse_arg_files(files)
if not tags:
raise ValueError(f"{self.__class__.__name__}.set_tags: argument 'tags' cannot be empty")
elif not isinstance(tags, dict):
raise TypeError(f"{self.__class__.__name__}.set_tags: argument 'tags' must be a dict")
if self._check_tag_names:
# run check if enabled
self.__class__._check_tag_list(list(tags)) # gets only the keys (tag names)
exec_params: List = []
# we extend an empty list to avoid modifying any referenced inputs
if params:
if _is_iterable(params, ignore_str_bytes=True):
exec_params.extend(params)
else:
exec_params.append(params)
for tag, value in tags.items():
# contributed by @daviddorme in https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234
# allows setting things like Keywords which require separate directives
# > exiftool -Keywords=keyword1 -Keywords=keyword2 -Keywords=keyword3 file.jpg
# which are not supported as duplicate keys in a dictionary
if isinstance(value, list):
for item in value:
exec_params.append(f"-{tag}={item}")
else:
exec_params.append(f"-{tag}={value}")
exec_params.extend(final_files)
try:
return self.execute(*exec_params)
#TODO if execute returns data, then error?
except ExifToolExecuteError:
# last status non-zero
raise
# ----------------------------------------------------------------------------------------------------------------------
#########################################################################################
#################################### PRIVATE METHODS ####################################
#########################################################################################
# ----------------------------------------------------------------------------------------------------------------------
@staticmethod
def _parse_arg_files(files: Union[str, List]) -> List:
"""
This logic to process the files argument is common across most ExifToolHelper methods
It can be used by a developer to process the files argument the same way if this class is extended
:param files: File(s) to be worked on.
:type files: str or list
:return: A list of one or more elements containing strings of files
:raises ValueError: Files parameter is empty
"""
final_files: List = []
if not files:
# Exiftool process would return an error anyways
raise ValueError("ERROR: Argument 'files' cannot be empty")
elif not _is_iterable(files, ignore_str_bytes=True):
# if it's not a string but also not iterable
final_files = [files]
else:
final_files = files
return final_files
# ----------------------------------------------------------------------------------------------------------------------
@staticmethod
def _check_tag_list(tags: List) -> None:
"""
Private method. This method is used to check the validity of a tag list passed in.
See any notes/warnings in the property :py:attr:`check_tag_names` to get a better understanding of what this is for and not for.
:param list tags: List of tags to check
:return: None if checks passed. Raises an error otherwise. (Think of it like an assert statement)
"""
# In the future if a specific version changed the match pattern,
# we can check self.version ... then this method will no longer
# be static and requires the underlying exiftool process to be running to get the self.version
#
# This is not done right now because the odds of the tag name format changing is very low, and requiring
# exiftool to be running during this tag check could introduce unneccesary overhead at this time
# According to the exiftool source code, the valid regex on tags is (/^([-\w*]+:)*([-\w*?]+)#?$/)
# However, it appears that "-" may be allowed within a tag name/group (i.e. https://exiftool.org/TagNames/XMP.html Description tags)
#
# \w in Perl => https://perldoc.perl.org/perlrecharclass#Backslash-sequences
# \w in Python => https://docs.python.org/3/library/re.html#regular-expression-syntax
#
# Perl vs Python's "\w" seem to mean slightly different things, so we write our own regex / matching algorithm
# * make sure the first character is not a special one
# * "#" can only appear at the end
# * Tag:Tag:tag is not valid, but passes the simple regex (it's ok, this is not supposed to be a catch-all)... exiftool subprocess accepts it anyways, even if invalid.
# * *wildcard* tags are permitted by exiftool
tag_regex = r"[\w\*][\w\:\-\*]*(#|)"
for t in tags:
if re.fullmatch(tag_regex, t) is None:
raise ExifToolTagNameError(t)
# returns nothing, if no error was raised, the tags passed
# considering making this...
# * can't begin with -
# * can't have "=" anywhere, and that's it...
# there's a lot of variations which might make this code buggy for some edge use cases
# ----------------------------------------------------------------------------------------------------------------------
================================================
FILE: mypy.ini
================================================
;[mypy-json.*]
;ignore_no_redef = True
================================================
FILE: scripts/README.txt
================================================
These are standardized scripts/batch files which run tests, code reviews, or other maintenance tasks in a repeatable way.
While scripts could automatically install requirements, it is left up to the caller: