├── .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 ├── rose.jpg └── skyblue.png ├── 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 /.github/workflows/lint-and-test.yml: -------------------------------------------------------------------------------- 1 | name: Lint and Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-20.04 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | python-version: [3.6, 3.7, 3.8, 3.9, '3.10', 3.11, 3.12] 13 | 14 | env: 15 | exiftool_version: 12.15 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | # while https://github.com/actions/setup-python recommends using a specific dependency version to use cache 24 | # we'll see if this just uses it in default configuration 25 | # this can't be enabled unless a requirements.txt file exists. PyExifTool doesn't have any hard requirements 26 | #cache: 'pip' 27 | - name: Cache Perl ExifTool Download 28 | # https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows 29 | uses: actions/cache@v2 30 | env: 31 | cache-name: cache-perl-exiftool 32 | with: 33 | # path where we would extract the ExifTool source files 34 | path: Image-ExifTool-${{ env.exiftool_version }} 35 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.exiftool_version }} 36 | 37 | - name: Install dependencies 38 | run: | 39 | # don't have to do this on the GitHub runner, it's going to always be the latest 40 | #python -m pip install --upgrade pip 41 | # the setup-python uses it this way instead of calling it via module, so maybe this will cache ... 42 | pip install flake8 pytest 43 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 44 | 45 | # latest version not yet available on Ubuntu Focal 20.04 LTS, but it's better to install it with all dependencies first 46 | sudo apt-get install -qq libimage-exiftool-perl 47 | # print this in the log 48 | exiftool -ver 49 | 50 | # get just the minimum version to build and compile, later we can go with latest version to test 51 | # working with cache: only get if the directory doesn't exist 52 | 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 53 | # extract if it was downloaded 54 | if [ -f Image-ExifTool-${{ env.exiftool_version }}.tar.gz ]; then tar xf Image-ExifTool-${{ env.exiftool_version }}.tar.gz; fi 55 | 56 | cd Image-ExifTool-${{ env.exiftool_version }}/ 57 | 58 | # https://exiftool.org/install.html#Unix 59 | perl Makefile.PL 60 | make test 61 | 62 | export PATH=`pwd`:$PATH 63 | cd .. 64 | exiftool -ver 65 | 66 | # save this environment for subsequent steps 67 | # https://brandur.org/fragments/github-actions-env-vars-in-env-vars 68 | echo "PATH=`pwd`:$PATH" >> $GITHUB_ENV 69 | - name: Install pyexiftool 70 | run: | 71 | # install all supported json processors for tests 72 | python -m pip install .[json,test] 73 | - name: Lint with flake8 74 | run: | 75 | # stop the build if there are Python syntax errors or undefined names 76 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 77 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 78 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 79 | - name: Test with pytest 80 | run: | 81 | pytest 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__/ 3 | build/ 4 | dist/ 5 | MANIFEST 6 | 7 | *.egg-info/ 8 | 9 | # pytest-cov db 10 | .coverage 11 | 12 | # tests will be made to write to temp directories with this prefix 13 | tests/exiftool-tmp-* 14 | 15 | # IntelliJ 16 | .idea 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # PyExifTool Changelog 2 | 3 | Date (Timezone) | Version | Comment 4 | ---------------------------- | ------- | ------- 5 | 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 6 | 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. 7 | 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. 8 | 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. 9 | 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. 10 | 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. 11 | 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) 12 | 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. 13 | 14 | 15 | Follow maintenance/release-process.html when releasing a version. 16 | 17 | 18 | # PyExifTool Changelog Archive (v0.2 - v0.4) 19 | 20 | Date (Timezone) | Version | Comment 21 | ---------------------------- | ------- | ------- 22 | 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 23 | 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) 24 | 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.* 25 | 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.* 26 | 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 27 | 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** 28 | 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 29 | 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) 30 | 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 31 | 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) 32 | 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 33 | 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 34 | 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** 35 | 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. 36 | 07/19/2019 12:01:22 AM (PDT) | 0.3.2 | fix the select() problem for windows, and fix all tests 37 | 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 38 | 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* 39 | 07/19/2019 01:22:48 AM (PDT) | 0.3.5 | changed a bit of the test_exiftool so all the tests pass again 40 | 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" 41 | 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 42 | 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! 43 | 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 44 | 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 45 | 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 46 | 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 47 | 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 48 | 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 49 | 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 50 | 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 51 | 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 52 | 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 53 | 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 54 | 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 55 | 56 | 57 | 58 | 59 | # Changes around the web 60 | 61 | 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! 62 | 63 | We can also direct users here or answer existing questions as to how to use the original version of ExifTool. 64 | 65 | (last checked 10/23/2023 all) 66 | 67 | search "pyexiftool github" to see if you find any more random ports/forks 68 | check for updates https://github.com/smarnach/pyexiftool/pulls 69 | check for new open issues https://github.com/smarnach/pyexiftool/issues?q=is%3Aissue+is%3Aopen 70 | 71 | answer relevant issues on stackoverflow (make sure it's related to the latest version) https://stackoverflow.com/search?tab=newest&q=pyexiftool&searchOn=3 72 | -------------------------------------------------------------------------------- /COMPATIBILITY.txt: -------------------------------------------------------------------------------- 1 | PyExifTool does not guarantee source-level compatibility from one release to the next. 2 | 3 | That said, efforts will be made to provide well-documented API-level compatibility, 4 | and if there are major API changes, migration documentation will be provided, when 5 | possible. 6 | 7 | ---- 8 | 9 | v0.1.x - v0.2.0 = smarnach code, API compatible 10 | v0.2.1 - v0.4.13 = original v0.2 code with all PRs, a superset of functionality on Exiftool class 11 | v0.5.0 - = not API compatible with the v0.4.x series. Broke down functionality stability by classes. See comments below: 12 | 13 | 14 | ---- 15 | API changes between v0.4.x and v0.5.0: 16 | 17 | PYTHON CHANGE: Old: Python 2.6 supported. New: Python 3.6+ required 18 | 19 | CHANGED: Exiftool constructor: 20 | RENAME: "executable_" parameter to "executable" 21 | 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. 22 | DEFAULT: Old: "win_shell" defaults to True. New: "win_shell" defaults to False. 23 | NEW: "encoding" parameter 24 | NEW: "logger" parameter 25 | 26 | NEW PROPERTY GET/SET: a lot of properties were added to do get/set validation, and parameters can be changed outside of the constructor. 27 | 28 | METHOD RENAME: starting the process was renamed from "start" to "run" 29 | 30 | MINIMUM TOOL VERSION: exiftool command line utility minimum requirements. Old: 8.60. New: 12.15 31 | 32 | ENCODING CHANGE: execute() and execute_json() no longer take bytes, but is guided by the encoding set in constructor/property 33 | 34 | ERROR CHANGE: execute_json() when no json was not returned (such as a set metadata operation) => Old: raised an error. New: returns custom ExifToolException 35 | 36 | FEATURE REMOVAL: execute_json() no longer detects the '-w' flag being passed used in common_args. 37 | If a user uses this flag, expect no output. 38 | (detection in common_args was clunky anyways because -w can be passed as a per-run param for the same effect) 39 | 40 | 41 | all methods other than execute() and execute_json() moved to ExifToolHelper or ExifToolAlpha class. 42 | 43 | ExifToolHelper adds methods: 44 | get_metadata() 45 | get_tags() 46 | 47 | NEW CONVENTION: all methods take "files" first, "tags" second (if needed) and "params" last 48 | 49 | 50 | ExifToolAlpha adds all remaining methods in an alpha-quality way 51 | 52 | NOTE: ExifToolAlpha has not been updated yet to use the new convention, and the edge case code may be removed/changed at any time. 53 | 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 54 | ---- 55 | 56 | -------------------------------------------------------------------------------- /COPYING.BSD: -------------------------------------------------------------------------------- 1 | Copyright 2012 Sven Marnach, 2019-2023 Kevin M (sylikc) 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | * Redistributions of source code must retain the above copyright notice, 7 | this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright notice, 9 | this list of conditions and the following disclaimer in the documentation 10 | and/or other materials provided with the distribution. 11 | * The names of its contributors may not be used to endorse or promote 12 | products derived from this software without specific prior written 13 | permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL SVEN MARNACH BE LIABLE FOR ANY DIRECT, INDIRECT, 19 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 20 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 21 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 22 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 23 | OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 24 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | PyExifTool 2 | 3 | Copyright 2019-2023 Kevin M (sylikc) 4 | Copyright 2012-2014 Sven Marnach 5 | 6 | PyExifTool is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the licence, or 9 | (at your option) any later version, or the BSD licence. 10 | 11 | PyExifTool is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 14 | 15 | See COPYING.GPL or COPYING.BSD for more details. 16 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst COPYING doc/Makefile doc/conf.py doc/*.rst 2 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ********** 2 | PyExifTool 3 | ********** 4 | 5 | .. image:: https://img.shields.io/badge/Docs-latest-blueviolet 6 | :alt: GitHub Pages 7 | :target: http://sylikc.github.io/pyexiftool/ 8 | 9 | 10 | .. HIDE_FROM_PYPI_START 11 | 12 | .. image:: https://github.com/sylikc/pyexiftool/actions/workflows/lint-and-test.yml/badge.svg 13 | :alt: GitHub Actions 14 | :target: https://github.com/sylikc/pyexiftool/actions 15 | 16 | .. image:: https://img.shields.io/pypi/v/pyexiftool.svg 17 | :target: https://pypi.org/project/PyExifTool/ 18 | :alt: PyPI Version 19 | 20 | 21 | .. HIDE_FROM_PYPI_END 22 | 23 | .. image:: https://img.shields.io/pypi/pyversions/pyexiftool.svg 24 | :target: https://pypi.org/project/PyExifTool/ 25 | :alt: Supported Python Versions 26 | 27 | .. image:: https://pepy.tech/badge/pyexiftool 28 | :target: https://pepy.tech/project/pyexiftool 29 | :alt: Total PyPI Downloads 30 | 31 | .. image:: https://static.pepy.tech/personalized-badge/pyexiftool?period=month&units=international_system&left_color=black&right_color=orange&left_text=Downloads%2030d 32 | :target: https://pepy.tech/project/pyexiftool 33 | :alt: PyPI Downloads this month 34 | 35 | 36 | 37 | .. DESCRIPTION_START 38 | 39 | .. BLURB_START 40 | 41 | PyExifTool is a Python library to communicate with an instance of 42 | `Phil Harvey's ExifTool`_ command-line application. 43 | 44 | .. _Phil Harvey's ExifTool: https://exiftool.org/ 45 | 46 | 47 | .. BLURB_END 48 | 49 | The library provides the class ``exiftool.ExifTool`` that runs the command-line 50 | tool in batch mode and features methods to send commands to that 51 | program, including methods to extract meta-information from one or 52 | more image files. Since ``exiftool`` is run in batch mode, only a 53 | single instance needs to be launched and can be reused for many 54 | queries. This is much more efficient than launching a separate 55 | process for every single query. 56 | 57 | 58 | .. DESCRIPTION_END 59 | 60 | .. contents:: 61 | :depth: 2 62 | :backlinks: none 63 | 64 | Example Usage 65 | ============= 66 | 67 | Simple example: :: 68 | 69 | import exiftool 70 | 71 | files = ["a.jpg", "b.png", "c.tif"] 72 | with exiftool.ExifToolHelper() as et: 73 | metadata = et.get_metadata(files) 74 | for d in metadata: 75 | print("{:20.20} {:20.20}".format(d["SourceFile"], 76 | d["EXIF:DateTimeOriginal"])) 77 | 78 | Refer to documentation for more `Examples and Quick Start Guide`_ 79 | 80 | .. _`Examples and Quick Start Guide`: http://sylikc.github.io/pyexiftool/examples.html 81 | 82 | 83 | .. INSTALLATION_START 84 | 85 | Getting PyExifTool 86 | ================== 87 | 88 | PyPI 89 | ------------ 90 | 91 | Easiest: Install a version from the official `PyExifTool PyPI`_ 92 | 93 | :: 94 | 95 | python -m pip install -U pyexiftool 96 | 97 | .. _PyExifTool PyPI: https://pypi.org/project/PyExifTool/ 98 | 99 | 100 | From Source 101 | ------------ 102 | 103 | #. Check out the source code from the github repository 104 | 105 | * ``git clone git://github.com/sylikc/pyexiftool.git`` 106 | * Alternatively, you can download a tarball_. 107 | 108 | #. Run setup.py to install the module from source 109 | 110 | * ``python setup.py install [--user|--prefix=]`` 111 | 112 | 113 | .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master 114 | 115 | 116 | PyExifTool Dependencies 117 | ======================= 118 | 119 | Python 120 | ------ 121 | 122 | PyExifTool runs on **Python 3.6+**. (If you need Python 2.6 support, 123 | please use version v0.4.x). PyExifTool has been tested on Windows and 124 | Linux, and probably also runs on other Unix-like platforms. 125 | 126 | Phil Harvey's exiftool 127 | ---------------------- 128 | 129 | For PyExifTool to function, ``exiftool`` command-line tool must exist on 130 | the system. If ``exiftool`` is not on the ``PATH``, you can specify the full 131 | pathname to it by using ``ExifTool(executable=)``. 132 | 133 | PyExifTool requires a **minimum version of 12.15** (which was the first 134 | production version of exiftool featuring the options to allow exit status 135 | checks used in conjuction with ``-echo3`` and ``-echo4`` parameters). 136 | 137 | To check your ``exiftool`` version: 138 | 139 | :: 140 | 141 | exiftool -ver 142 | 143 | 144 | Windows/Mac 145 | ^^^^^^^^^^^ 146 | 147 | Windows/Mac users can download the latest version of exiftool: 148 | 149 | :: 150 | 151 | https://exiftool.org 152 | 153 | Linux 154 | ^^^^^ 155 | 156 | Most current Linux distributions have a package which will install ``exiftool``. 157 | Unfortunately, some do not have the minimum required version, in which case you 158 | will have to `build from source`_. 159 | 160 | * Ubuntu 161 | :: 162 | 163 | sudo apt install libimage-exiftool-perl 164 | 165 | * CentOS/RHEL 166 | :: 167 | 168 | yum install perl-Image-ExifTool 169 | 170 | .. _build from source: https://exiftool.org/install.html#Unix 171 | 172 | 173 | .. INSTALLATION_END 174 | 175 | 176 | Documentation 177 | ============= 178 | 179 | The current documentation is available at `sylikc.github.io`_. 180 | 181 | :: 182 | 183 | http://sylikc.github.io/pyexiftool/ 184 | 185 | .. _sylikc.github.io: http://sylikc.github.io/pyexiftool/ 186 | 187 | 188 | Package Structure 189 | ----------------- 190 | 191 | .. DESIGN_INFO_START 192 | 193 | PyExifTool was designed with flexibility and extensibility in mind. The library consists of a few classes, each with increasingly more features. 194 | 195 | The base ``ExifTool`` class contains the core functionality exposed in the most rudimentary way, and each successive class inherits and adds functionality. 196 | 197 | .. DESIGN_INFO_END 198 | 199 | .. DESIGN_CLASS_START 200 | 201 | * ``exiftool.ExifTool`` is the base class with core logic to interface with PH's ExifTool process. 202 | It contains only the core features with no extra fluff. 203 | The main methods provided are ``execute()`` and ``execute_json()`` which allows direct interaction with the underlying exiftool process. 204 | 205 | * The API is considered stable and should not change much with future releases. 206 | 207 | * ``exiftool.ExifToolHelper`` exposes some of the most commonly used functionality. It overloads 208 | some inherited functions to turn common errors into warnings and adds logic to make 209 | ``exiftool.ExifTool`` easier to use. 210 | 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). 211 | ``ExifToolHelper`` demonstrates how to extend ``ExifTool`` to your liking if your project demands customizations not directly provided by ``ExifTool``. 212 | 213 | * More methods may be added and/or slight API tweaks may occur with future releases. 214 | 215 | * ``exiftool.ExifToolAlpha`` further extends the ``ExifToolHelper`` and includes some community-contributed not-very-well-tested methods. 216 | These methods were formerly added ad-hoc by various community contributors, but no longer stand up to the rigor of the current design. 217 | ``ExifToolAlpha`` is *not* up to the rigorous testing standard of both 218 | ``ExifTool`` or ``ExifToolHelper``. There may be old, buggy, or defunct code. 219 | 220 | * This is the least polished of the classes and functionality/API may be changed/added/removed on any release. 221 | 222 | * **NOTE: The methods exposed may be changed/removed at any time.** 223 | 224 | * 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``. 225 | (Think of ``ExifToolAlpha`` as ideas on how to extend ``ExifTool``, where new functionality which may one day make it into the ``ExifToolHelper`` class.) 226 | 227 | .. _Submit an Issue: https://github.com/sylikc/pyexiftool/issues 228 | 229 | 230 | .. DESIGN_CLASS_END 231 | 232 | 233 | Brief History 234 | ============= 235 | 236 | .. HISTORY_START 237 | 238 | PyExifTool was originally developed by `Sven Marnach`_ in 2012 to answer a 239 | stackoverflow question `Call exiftool from a python script?`_. Over time, 240 | Sven refined the code, added tests, documentation, and a slew of improvements. 241 | While PyExifTool gained popularity, Sven `never intended to maintain it`_ as 242 | an active project. The `original repository`_ was last updated in 2014. 243 | 244 | Over the years, numerous issues were filed and several PRs were opened on the 245 | stagnant repository. In early 2019, `Martin Čarnogurský`_ created a 246 | `PyPI release`_ from the 2014 code with some minor updates. Coincidentally in 247 | mid 2019, `Kevin M (sylikc)`_ forked the original repository and started merging 248 | the PR and issues which were reported on Sven's issues/PR page. 249 | 250 | In late 2019 and early 2020 there was a discussion started to 251 | `Provide visibility for an active fork`_. There was a conversation to 252 | transfer ownership of the original repository, have a coordinated plan to 253 | communicate to PyExifTool users, amongst other things, but it never materialized. 254 | 255 | Kevin M (sylikc) made the first release to the PyPI repository in early 2021. 256 | At the same time, discussions were started, revolving around 257 | `Deprecating Python 2.x compatibility`_ and `refactoring the code and classes`_. 258 | 259 | The latest version is the result of all of those discussions, designs, 260 | and development. Special thanks to the community contributions, especially 261 | `Jan Philip Göpfert`_, `Seth P`_, and `Kolen Cheung`_. 262 | 263 | .. _Sven Marnach: https://github.com/smarnach/pyexiftool 264 | .. _Call exiftool from a python script?: https://stackoverflow.com/questions/10075115/call-exiftool-from-a-python-script/10075210#10075210 265 | .. _never intended to maintain it: https://github.com/smarnach/pyexiftool/pull/31#issuecomment-569238073 266 | .. _original repository: https://github.com/smarnach/pyexiftool 267 | .. _Martin Čarnogurský: https://github.com/RootLUG 268 | .. _PyPI release: https://pypi.org/project/PyExifTool/0.1.1/#history 269 | .. _Kevin M (sylikc): https://github.com/sylikc 270 | .. _Provide visibility for an active fork: https://github.com/smarnach/pyexiftool/pull/31 271 | .. _Deprecating Python 2.x compatibility: https://github.com/sylikc/pyexiftool/discussions/9 272 | .. _refactoring the code and classes: https://github.com/sylikc/pyexiftool/discussions/10 273 | .. _Jan Philip Göpfert: https://github.com/jangop 274 | .. _Seth P: https://github.com/csparker247 275 | .. _Kolen Cheung: https://github.com/ickc 276 | 277 | 278 | .. HISTORY_END 279 | 280 | Licence 281 | ======= 282 | 283 | .. LICENSE_START 284 | 285 | PyExifTool is free software: you can redistribute it and/or modify 286 | it under the terms of the GNU General Public License as published by 287 | the Free Software Foundation, either version 3 of the licence, or 288 | (at your option) any later version, or the BSD licence. 289 | 290 | PyExifTool is distributed in the hope that it will be useful, 291 | but WITHOUT ANY WARRANTY; without even the implied warranty of 292 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 293 | 294 | See ``LICENSE`` for more details. 295 | 296 | 297 | .. LICENSE_END 298 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | _build/ 2 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | SOURCEDIR = source 9 | BUILDDIR = _build 10 | 11 | # Internal variables. 12 | PAPEROPT_a4 = -D latex_paper_size=a4 13 | PAPEROPT_letter = -D latex_paper_size=letter 14 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 15 | # the i18n builder cannot share the environment and doctrees with the others 16 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 17 | 18 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 19 | 20 | help: 21 | @echo "Please use \`make ' where is one of" 22 | @echo " html to make standalone HTML files" 23 | @echo " dirhtml to make HTML files named index.html in directories" 24 | @echo " singlehtml to make a single large HTML file" 25 | @echo " pickle to make pickle files" 26 | @echo " json to make JSON files" 27 | @echo " htmlhelp to make HTML files and a HTML help project" 28 | @echo " qthelp to make HTML files and a qthelp project" 29 | @echo " devhelp to make HTML files and a Devhelp project" 30 | @echo " epub to make an epub" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " text to make text files" 34 | @echo " man to make manual pages" 35 | @echo " texinfo to make Texinfo files" 36 | @echo " info to make Texinfo files and run them through makeinfo" 37 | @echo " gettext to make PO message catalogs" 38 | @echo " changes to make an overview of all changed/added/deprecated items" 39 | @echo " linkcheck to check all external links for integrity" 40 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 41 | 42 | clean: 43 | -rm -rf $(BUILDDIR)/* 44 | 45 | html: 46 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 47 | @echo 48 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 49 | 50 | dirhtml: 51 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 52 | @echo 53 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 54 | 55 | singlehtml: 56 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 57 | @echo 58 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 59 | 60 | pickle: 61 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 62 | @echo 63 | @echo "Build finished; now you can process the pickle files." 64 | 65 | json: 66 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 67 | @echo 68 | @echo "Build finished; now you can process the JSON files." 69 | 70 | htmlhelp: 71 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 72 | @echo 73 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 74 | ".hhp project file in $(BUILDDIR)/htmlhelp." 75 | 76 | qthelp: 77 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 78 | @echo 79 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 80 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 81 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyExifTool.qhcp" 82 | @echo "To view the help file:" 83 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyExifTool.qhc" 84 | 85 | devhelp: 86 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 87 | @echo 88 | @echo "Build finished." 89 | @echo "To view the help file:" 90 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PyExifTool" 91 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyExifTool" 92 | @echo "# devhelp" 93 | 94 | epub: 95 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 96 | @echo 97 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 98 | 99 | latex: 100 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 101 | @echo 102 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 103 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 104 | "(use \`make latexpdf' here to do that automatically)." 105 | 106 | latexpdf: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo "Running LaTeX files through pdflatex..." 109 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 110 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 111 | 112 | text: 113 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 114 | @echo 115 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 116 | 117 | man: 118 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 119 | @echo 120 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 121 | 122 | texinfo: 123 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 124 | @echo 125 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 126 | @echo "Run \`make' in that directory to run these through makeinfo" \ 127 | "(use \`make info' here to do that automatically)." 128 | 129 | info: 130 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 131 | @echo "Running Texinfo files through makeinfo..." 132 | make -C $(BUILDDIR)/texinfo info 133 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 134 | 135 | gettext: 136 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 137 | @echo 138 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 139 | 140 | changes: 141 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 142 | @echo 143 | @echo "The overview file is in $(BUILDDIR)/changes." 144 | 145 | linkcheck: 146 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 147 | @echo 148 | @echo "Link check complete; look for any errors in the above output " \ 149 | "or in $(BUILDDIR)/linkcheck/output.txt." 150 | 151 | doctest: 152 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 153 | @echo "Testing of doctests in the sources finished, look at the " \ 154 | "results in $(BUILDDIR)/doctest/output.txt." 155 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sylikc/pyexiftool/e54f96cd75758096f72bc97c42390f1f9fef8010/docs/source/conf.py -------------------------------------------------------------------------------- /docs/source/examples.rst: -------------------------------------------------------------------------------- 1 | ********************** 2 | Examples / Quick Start 3 | ********************** 4 | 5 | .. NOTE: No tabs in this file, all spaces, to simplify examples indentation 6 | 7 | 8 | Try it yourself: All of these examples are using the images provided in the `tests directory`_ in the source 9 | 10 | .. _`tests directory`: https://github.com/sylikc/pyexiftool/tree/master/tests/images 11 | 12 | 13 | 14 | Understanding input and output from PyExifTool base methods 15 | =========================================================== 16 | 17 | Almost all methods in PyExifTool revolve around the usage of two methods from the base :py:class:`exiftool.ExifTool` class. 18 | 19 | 20 | **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) 21 | 22 | .. note:: 23 | 24 | Because both methods are inherited by :py:class:`exiftool.ExifToolHelper` and :py:class:`exiftool.ExifToolAlpha`, you can call it from those classes as well. 25 | 26 | 27 | .. _examples input params: 28 | 29 | Input parameters 30 | ---------------- 31 | 32 | Both methods take an argument list ``*args``. Examples: 33 | 34 | .. note:: 35 | 36 | 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. 37 | 38 | 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 ` 39 | 40 | * Calling directly: 41 | 42 | * exiftool command-line: 43 | 44 | .. code-block:: text 45 | 46 | exiftool -XMPToolKit -Subject rose.jpg 47 | 48 | * PyExifTool: 49 | 50 | .. code-block:: 51 | 52 | execute("-XMPToolKit", "-Subject", "rose.jpg") 53 | 54 | * Using argument unpacking of a list: 55 | 56 | * exiftool command-line: 57 | 58 | .. code-block:: text 59 | 60 | exiftool -P -DateTimeOriginal="2021:01:02 03:04:05" -MakerNotes= "spaces in filename.jpg" 61 | 62 | * PyExifTool: 63 | 64 | .. note:: 65 | 66 | 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. 67 | 68 | In this example, *DateTimeOriginal* value is not quoted in the parameter to execute(). 69 | 70 | .. code-block:: 71 | 72 | execute(*["-P", "-DateTimeOriginal=2021:01:02 03:04:05", "-MakerNotes=", "spaces in filename.jpg"]) 73 | 74 | 75 | * Getting JSON output using argument unpacking of a list: 76 | 77 | * exiftool command-line: 78 | 79 | .. code-block:: text 80 | 81 | exiftool -j -XMP:all -JFIF:JFIFVersion /path/somefile.jpg 82 | 83 | * PyExifTool: 84 | 85 | .. code-block:: 86 | 87 | execute_json(*["-XMP:all", "-JFIF:JFIFVersion", "/path/somefile.jpg"]) 88 | 89 | 90 | Output values 91 | ------------- 92 | 93 | * :py:meth:`exiftool.ExifTool.execute_json` 94 | 95 | * Returns a ``list`` of ``dict`` 96 | * Each ``dict`` is a result from a file 97 | * Each ``dict`` contains a key "SourceFile" which points to the relative or absolute file path of file 98 | * All other keys/value pairs are requested metadata 99 | 100 | * :py:meth:`exiftool.ExifTool.execute` 101 | 102 | * Returns a ``str`` 103 | * Typically used for **setting tags** as no values are returned in that case. 104 | 105 | 106 | ExifToolHelper 107 | ============== 108 | 109 | Using methods provided by :py:class:`exiftool.ExifToolHelper`: 110 | 111 | ExifToolHelper provides some of the most commonly used operations most people use *exiftool* for 112 | 113 | Getting Tags 114 | ------------ 115 | 116 | * Get all tags on a single file 117 | 118 | .. code-block:: 119 | 120 | from exiftool import ExifToolHelper 121 | with ExifToolHelper() as et: 122 | for d in et.get_metadata("rose.jpg"): 123 | for k, v in d.items(): 124 | print(f"Dict: {k} = {v}") 125 | 126 | 127 | .. code-block:: text 128 | 129 | Dict: SourceFile = rose.jpg 130 | Dict: ExifTool:ExifToolVersion = 12.37 131 | Dict: File:FileName = rose.jpg 132 | Dict: File:Directory = . 133 | Dict: File:FileSize = 4949 134 | Dict: File:FileModifyDate = 2022:03:03 17:47:11-08:00 135 | Dict: File:FileAccessDate = 2022:03:27 08:28:16-07:00 136 | Dict: File:FileCreateDate = 2022:03:03 17:47:11-08:00 137 | Dict: File:FilePermissions = 100666 138 | Dict: File:FileType = JPEG 139 | Dict: File:FileTypeExtension = JPG 140 | Dict: File:MIMEType = image/jpeg 141 | Dict: File:ImageWidth = 70 142 | Dict: File:ImageHeight = 46 143 | Dict: File:EncodingProcess = 0 144 | Dict: File:BitsPerSample = 8 145 | Dict: File:ColorComponents = 3 146 | Dict: File:YCbCrSubSampling = 2 2 147 | Dict: JFIF:JFIFVersion = 1 1 148 | Dict: JFIF:ResolutionUnit = 1 149 | Dict: JFIF:XResolution = 72 150 | Dict: JFIF:YResolution = 72 151 | Dict: XMP:XMPToolkit = Image::ExifTool 8.85 152 | Dict: XMP:Subject = Röschen 153 | Dict: Composite:ImageSize = 70 46 154 | Dict: Composite:Megapixels = 0.00322 155 | 156 | * Get some tags in multiple files 157 | 158 | .. code-block:: 159 | 160 | from exiftool import ExifToolHelper 161 | with ExifToolHelper() as et: 162 | for d in et.get_tags(["rose.jpg", "skyblue.png"], tags=["FileSize", "ImageSize"]): 163 | for k, v in d.items(): 164 | print(f"Dict: {k} = {v}") 165 | 166 | 167 | .. code-block:: text 168 | 169 | Dict: SourceFile = rose.jpg 170 | Dict: File:FileSize = 4949 171 | Dict: Composite:ImageSize = 70 46 172 | Dict: SourceFile = skyblue.png 173 | Dict: File:FileSize = 206 174 | Dict: Composite:ImageSize = 64 64 175 | 176 | Setting Tags 177 | ------------ 178 | 179 | * Setting date and time of some files to current time, overwriting file, but preserving original mod date 180 | 181 | .. code-block:: 182 | 183 | from exiftool import ExifToolHelper 184 | from datetime import datetime 185 | with ExifToolHelper() as et: 186 | now = datetime.strftime(datetime.now(), "%Y:%m:%d %H:%M:%S") 187 | et.set_tags( 188 | ["rose.jpg", "skyblue.png"], 189 | tags={"DateTimeOriginal": now}, 190 | params=["-P", "-overwrite_original"] 191 | ) 192 | 193 | (*No output is returned if successful*) 194 | 195 | * Setting keywords for a file. 196 | 197 | .. code-block:: 198 | 199 | from exiftool import ExifToolHelper 200 | with ExifToolHelper() as et: 201 | et.set_tags( 202 | ["rose.jpg", "skyblue.png"], 203 | tags={"Keywords": ["sunny", "nice day", "cool", "awesome"]} 204 | ) 205 | 206 | (*No output is returned if successful*) 207 | 208 | 209 | 210 | Exceptions 211 | ---------- 212 | 213 | By default, ExifToolHelper has some **built-in error checking**, making the methods safer to use than calling the base methods directly. 214 | 215 | .. warning:: 216 | 217 | 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. 218 | 219 | * Example using get_tags() on a list which includes a non-existent file 220 | 221 | * ExifToolHelper with error-checking, using :py:meth:`exiftool.ExifToolHelper.get_tags` 222 | 223 | .. code-block:: 224 | 225 | from exiftool import ExifToolHelper 226 | with ExifToolHelper() as et: 227 | print(et.get_tags( 228 | ["rose.jpg", "skyblue.png", "non-existent file.tif"], 229 | tags=["FileSize"] 230 | )) 231 | 232 | Output: 233 | 234 | .. code-block:: text 235 | 236 | Traceback (most recent call last): 237 | File "T:\example.py", line 7, in 238 | et.get_tags(["rose.jpg", "skyblue.png", "non-existent file.tif"], tags=["FileSize"]) 239 | File "T:\pyexiftool\exiftool\helper.py", line 353, in get_tags 240 | ret = self.execute_json(*exec_params) 241 | File "T:\pyexiftool\exiftool\exiftool.py", line 1030, in execute_json 242 | result = self.execute("-j", *params) # stdout 243 | File "T:\pyexiftool\exiftool\helper.py", line 119, in execute 244 | raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, params) 245 | exiftool.exceptions.ExifToolExecuteError: execute returned a non-zero exit status: 1 246 | 247 | 248 | * 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.**) 249 | 250 | .. code-block:: 251 | 252 | from exiftool import ExifToolHelper 253 | with ExifToolHelper() as et: 254 | print(et.get_tags( 255 | ["rose.jpg", "skyblue.png", "non-existent file.tif"], 256 | tags=["FileSize"] 257 | )) 258 | 259 | Output: 260 | 261 | .. code-block:: text 262 | 263 | [{'SourceFile': 'rose.jpg', 'File:FileSize': 4949}, {'SourceFile': 'skyblue.png', 'File:FileSize': 206}] 264 | 265 | 266 | * 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!)... 267 | 268 | * Using :py:meth:`exiftool.ExifToolHelper.get_tags` 269 | 270 | .. code-block:: 271 | 272 | from exiftool import ExifToolHelper 273 | with ExifToolHelper() as et: 274 | print(et.get_tags(["skyblue.png"], tags=["XMP:Subject=hi"])) 275 | 276 | Output: 277 | 278 | .. code-block:: text 279 | 280 | Traceback (most recent call last): 281 | File "T:\example.py", line 7, in 282 | print(et.get_tags(["skyblue.png"], tags=["XMP:Subject=hi"])) 283 | File "T:\pyexiftool\exiftool\helper.py", line 341, in get_tags 284 | self.__class__._check_tag_list(final_tags) 285 | File "T:\pyexiftool\exiftool\helper.py", line 574, in _check_tag_list 286 | raise ExifToolTagNameError(t) 287 | exiftool.exceptions.ExifToolTagNameError: Invalid Tag Name found: "XMP:Subject=hi" 288 | 289 | * Using :py:meth:`exiftool.ExifTool.execute_json`. It still raises an exception, but more cryptic and difficult to debug 290 | 291 | .. code-block:: 292 | 293 | from exiftool import ExifTool 294 | with ExifTool() as et: 295 | print(et.execute_json(*["-XMP:Subject=hi"] + ["skyblue.png"])) 296 | 297 | Output: 298 | 299 | .. code-block:: text 300 | 301 | Traceback (most recent call last): 302 | File "T:\example.py", line 7, in 303 | print(et.execute_json(*["-XMP:Subject=hi"] + ["skyblue.png"])) 304 | File "T:\pyexiftool\exiftool\exiftool.py", line 1052, in execute_json 305 | raise ExifToolOutputEmptyError(self._last_status, self._last_stdout, self._last_stderr, params) 306 | exiftool.exceptions.ExifToolOutputEmptyError: execute_json expected output on stdout but got none 307 | 308 | * Using :py:meth:`exiftool.ExifTool.execute`. **No errors, but you have now written to the file instead of reading from it!** 309 | 310 | .. code-block:: 311 | 312 | from exiftool import ExifTool 313 | with ExifTool() as et: 314 | print(et.execute(*["-XMP:Subject=hi"] + ["skyblue.png"])) 315 | 316 | Output: 317 | 318 | .. code-block:: text 319 | 320 | 1 image files updated 321 | 322 | ExifTool 323 | ======== 324 | 325 | Using methods provided by :py:class:`exiftool.ExifTool` 326 | 327 | Calling execute() or execute_json() provides raw functionality for advanced use cases. Use with care! 328 | 329 | 330 | 331 | .. TODO show some ExifTool and ExifToolHelper use cases for common exiftool operations 332 | 333 | .. TODO show some Advanced use cases, and maybe even some don't-do-this-even-though-you-can cases (like using params for tags) 334 | 335 | -------------------------------------------------------------------------------- /docs/source/faq.rst: -------------------------------------------------------------------------------- 1 | ************************** 2 | Frequently Asked Questions 3 | ************************** 4 | 5 | PyExifTool output is different from the exiftool command line 6 | ============================================================= 7 | 8 | One of the most frequently asked questions relates to the *default output* of PyExifTool. 9 | 10 | For example, using the `rose.jpg in tests`_, let's get **all JFIF tags**: 11 | 12 | Default exiftool output 13 | ----------------------- 14 | 15 | $ ``exiftool -JFIF:all rose.jpg`` 16 | 17 | .. code-block:: text 18 | 19 | JFIF Version : 1.01 20 | Resolution Unit : inches 21 | X Resolution : 72 22 | Y Resolution : 72 23 | 24 | 25 | .. _`rose.jpg in tests`: https://github.com/sylikc/pyexiftool/blob/master/tests/files/rose.jpg 26 | 27 | Default PyExifTool output 28 | ------------------------- 29 | 30 | from PyExifTool, using the following code: 31 | 32 | .. code-block:: 33 | 34 | import exiftool 35 | with exiftool.ExifTool() as et: 36 | print(et.execute("-JFIF:all", "rose.jpg")) 37 | 38 | Output: 39 | 40 | .. code-block:: text 41 | 42 | [JFIF] JFIF Version : 1 1 43 | [JFIF] Resolution Unit : 1 44 | [JFIF] X Resolution : 72 45 | [JFIF] Y Resolution : 72 46 | 47 | What's going on? 48 | ---------------- 49 | 50 | The reason for the different default output is that PyExifTool, by default, includes two arguments which make *exiftool* easier to use: ``-G, -n``. 51 | 52 | .. note:: 53 | 54 | The ``-n`` disables *print conversion* which displays **raw tag values**, making the output more **machine-parseable**. 55 | 56 | When *print conversion* is enabled, *some* raw values may be translated to prettier **human-readable** text. 57 | 58 | 59 | .. note:: 60 | 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. 61 | 62 | 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*. 63 | 64 | 65 | Read the documentation for the ExifTool constructor ``common_args`` parameter for more details: :py:meth:`exiftool.ExifTool.__init__`. 66 | 67 | (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`) 68 | 69 | 70 | 71 | 72 | Ways to make the ouptut match 73 | ----------------------------- 74 | 75 | So if you want to have the ouput match (*useful for debugging*) between PyExifTool and exiftool, either: 76 | 77 | * **Enable print conversion on exiftool command line**: 78 | 79 | $ ``exiftool -G -n -JFIF:all rose.jpg`` 80 | 81 | .. code-block:: text 82 | 83 | [JFIF] JFIF Version : 1 1 84 | [JFIF] Resolution Unit : 1 85 | [JFIF] X Resolution : 72 86 | [JFIF] Y Resolution : 72 87 | 88 | * **Disable print conversion and group name in PyExifTool**: 89 | 90 | .. code-block:: 91 | 92 | import exiftool 93 | with exiftool.ExifTool(common_args=None) as et: 94 | print(et.execute("-JFIF:all", "rose.jpg")) 95 | 96 | Output: 97 | 98 | .. code-block:: text 99 | 100 | JFIF Version : 1.01 101 | Resolution Unit : inches 102 | X Resolution : 72 103 | Y Resolution : 72 104 | 105 | 106 | 107 | .. _shlex split: 108 | 109 | I can run this on the command-line but it doesn't work in PyExifTool 110 | ==================================================================== 111 | 112 | A frequent problem encountered by first-time users, is figuring out how to properly split their arguments into a call to PyExifTool. 113 | 114 | As noted in the :ref:`Quick Start Examples `: 115 | 116 | If there is an **unquoted space on the command line** to *exiftool*, it's a **separate argument to the method** in PyExifTool. 117 | 118 | So, what does this look like in practice? 119 | 120 | 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. 121 | 122 | * Sample exiftool command line (with multiple quoted and unquoted parameters): 123 | 124 | .. code-block:: text 125 | 126 | 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 127 | 128 | * Using ``shlex`` to figure out the right argument list: 129 | 130 | .. code-block:: 131 | 132 | import shlex, exiftool 133 | with exiftool.ExifToolHelper() as et: 134 | 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') 135 | print(params) 136 | # 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'] 137 | et.execute(*params) 138 | 139 | .. note:: 140 | 141 | ``shlex.split()`` is a useful *tool to simplify discovery* of the correct arguments needed to call PyExifTool. 142 | 143 | However, since spliting and constructing immutable strings in Python is **slower than building the parameter list properly**, this method is *only recommended for* **debugging**! 144 | 145 | 146 | .. _`Python's shlex library`: https://docs.python.org/library/shlex.html 147 | 148 | .. _set_json_loads faq: 149 | 150 | PyExifTool json turns some text fields into numbers 151 | =================================================== 152 | 153 | A strange behavior of *exiftool* is documented in the `exiftool documentation`_:: 154 | 155 | -j[[+]=JSONFILE] (-json) 156 | 157 | Note that ExifTool quotes JSON values only if they don't look like numbers 158 | (regardless of the original storage format or the relevant metadata specification). 159 | 160 | .. _`exiftool documentation`: https://exiftool.org/exiftool_pod.html#OPTIONS 161 | 162 | This causes a peculiar behavior if you set a text metadata field to a string that looks like a number: 163 | 164 | .. code-block:: 165 | 166 | import exiftool 167 | with exiftool.ExifToolHelper() as et: 168 | # Comment is a STRING field 169 | et.set_tags("rose.jpg", {"Comment": "1.10"}) # string: "1.10" != "1.1" 170 | 171 | # FocalLength is a FLOAT field 172 | et.set_tags("rose.jpg", {"FocalLength": 1.10}) # float: 1.10 == 1.1 173 | print(et.get_tags("rose.jpg", ["Comment", "FocalLength"])) 174 | 175 | # Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': 1.1, 'EXIF:FocalLength': 1.1}] 176 | 177 | Workaround to enable output as string 178 | ------------------------------------- 179 | 180 | 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. 181 | 182 | 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. 183 | 184 | You can change the behavior of the json string parser, or specify a different one using :py:meth:`exiftool.ExifTool.set_json_loads`. 185 | 186 | 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. 187 | However, as you can see below, it also *changes the behavior of all float fields*. 188 | 189 | 190 | .. _`documentation of CPython's json.load`: https://docs.python.org/3/library/json.html#json.load 191 | 192 | .. code-block:: 193 | 194 | import exiftool, json 195 | with exiftool.ExifToolHelper() as et: 196 | et.set_json_loads(json.loads, parse_float=str) 197 | 198 | # Comment is a STRING field 199 | et.set_tags("rose.jpg", {"Comment": "1.10"}) # string: "1.10" == "1.10" 200 | 201 | # FocalLength is a FLOAT field 202 | et.set_tags("rose.jpg", {"FocalLength": 1.10}) # float: 1.1 != "1.1" 203 | print(et.get_tags("rose.jpg", ["Comment", "FocalLength"])) 204 | 205 | # Prints: [{'SourceFile': 'rose.jpg', 'File:Comment': '1.10', 'EXIF:FocalLength': '1.1'}] 206 | 207 | .. warning:: 208 | 209 | 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. 210 | 211 | There isn't any known universal workaround which wouldn't break one thing or the other, as it is an underlying *exiftool* quirk. 212 | 213 | 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, 214 | this workaround will allow you to configure PyExifTool to work in your environment! 215 | 216 | .. _`test cases related to numeric tags`: https://github.com/sylikc/pyexiftool/blob/master/tests/test_helper_tags_float.py 217 | 218 | 219 | I would like to use a faster json string parser 220 | =============================================== 221 | 222 | 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` 223 | 224 | 225 | .. code-block:: 226 | 227 | import exiftool, json 228 | with exiftool.ExifToolHelper() as et: 229 | et.set_json_loads(ujson.loads) 230 | ... 231 | 232 | .. note:: 233 | 234 | In PyExifTool version before 0.5.6, ``ujson`` was supported automatically if the package was installed. 235 | 236 | To support any possible alternative JSON library, this behavior has now been changed and it must be enabled manually. 237 | 238 | 239 | I'm getting an error! How do I debug PyExifTool output? 240 | ======================================================= 241 | 242 | 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. 243 | 244 | 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`_ 245 | 246 | 247 | .. _`Python logging - Advanced Logging Tutorial`: https://docs.python.org/3/howto/logging.html#advanced-logging-tutorial 248 | 249 | Example usage: 250 | 251 | .. code-block:: 252 | 253 | import logging 254 | import exiftool 255 | 256 | logging.basicConfig(level=logging.DEBUG) 257 | with exiftool.ExifToolHelper(logger=logging.getLogger(__name__)) as et: 258 | et.execute("missingfile.jpg",) 259 | 260 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. PyExifTool documentation master file, created by 2 | sphinx-quickstart on Thu Apr 12 17:42:54 2012. 3 | 4 | PyExifTool -- Python wrapper for Phil Harvey's ExifTool 5 | ======================================================= 6 | 7 | .. include:: ../../README.rst 8 | :start-after: BLURB_START 9 | :end-before: BLURB_END 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | :glob: 14 | :caption: Contents: 15 | 16 | intro 17 | package 18 | installation 19 | examples 20 | reference/* 21 | FAQ 22 | autoapi/* 23 | Source code on GitHub 24 | 25 | 26 | .. maintenance/* 27 | .. not public at the moment, at least it doesn't have to be in the TOC (adds unnecessary clutter) 28 | 29 | 30 | Indices and tables 31 | ================== 32 | * :ref:`genindex` 33 | * :ref:`modindex` 34 | * :ref:`search` 35 | -------------------------------------------------------------------------------- /docs/source/installation.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | Installation 3 | ************ 4 | 5 | .. include:: ../../README.rst 6 | :start-after: INSTALLATION_START 7 | :end-before: INSTALLATION_END 8 | -------------------------------------------------------------------------------- /docs/source/intro.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | Introduction 3 | ************ 4 | 5 | .. _introduction: 6 | 7 | .. include:: ../../README.rst 8 | :start-after: DESCRIPTION_START 9 | :end-before: DESCRIPTION_END 10 | 11 | Concepts 12 | ======== 13 | 14 | As noted in the :ref:`introduction `, PyExifTool is used to **communicate** with an instance of the external ExifTool process. 15 | 16 | .. note:: 17 | 18 | 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. 19 | 20 | .. _ExifTool by Phil Harvey: https://exiftool.org/ 21 | 22 | What PyExifTool Is 23 | ------------------ 24 | 25 | * ... is a wrapper for PH's Exiftool, hence it can do everything PH's ExifTool can do. 26 | * ... is a library which adds some helper functionality around ExifTool to make it easier to work with in Python. 27 | * ... is extensible and you can add functionality on top of the base class for your use case. 28 | * ... is supported on any platform which PH's ExifTool runs 29 | 30 | What PyExifTool Is NOT 31 | ---------------------- 32 | 33 | * ... is NOT a direct subtitute for Phil Harvey's ExifTool. The `exiftool` executable must still be installed and available for PyExifTool to use. 34 | * ... is NOT a library which does direct image manipulation (ex. Python Pillow_). 35 | 36 | .. _Pillow: https://pillow.readthedocs.io/en/stable/ 37 | 38 | Nomenclature 39 | ============ 40 | 41 | 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. 42 | Hence, here's some common nomenclature used. 43 | 44 | Because the term `exiftool` is overloaded (lowercase, CapWords case, ...) and can mean several things: 45 | 46 | * `PH's ExifTool` = Phil Harvey's ExifTool 47 | * ``ExifTool`` in context usually implies ``exiftool.ExifTool`` 48 | * `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) 49 | 50 | -------------------------------------------------------------------------------- /docs/source/maintenance/release-process.rst: -------------------------------------------------------------------------------- 1 | *************** 2 | Release Process 3 | *************** 4 | 5 | This page documents the steps to be taken to release a new version of PyExifTool. 6 | 7 | 8 | Source Preparation 9 | ================== 10 | 11 | #. Update the version number in ``exiftool/__init__.py`` 12 | #. Update the docs copyright year ``docs/source/conf.py`` and in source files 13 | #. Add any changelog entries to ``CHANGELOG.md`` 14 | #. Run Tests 15 | #. Generate docs 16 | #. Commit and push the changes. 17 | #. Check that the tests passed on GitHub. 18 | 19 | 20 | Pre-Requisites 21 | ============== 22 | 23 | Make sure the latest packages are installed. 24 | 25 | #. pip: ``python -m pip install --upgrade pip`` 26 | #. build tools: ``python -m pip install --upgrade setuptools build`` 27 | #. for uploading to PyPI: ``python -m pip install --upgrade twine`` 28 | 29 | Run Tests 30 | ========= 31 | 32 | #. Run in standard unittest: ``python -m unittest -v`` 33 | #. Run in PyTest: ``scripts\pytest.bat`` 34 | 35 | Build and Check 36 | =============== 37 | 38 | #. Build package: ``python -m build`` 39 | #. `Validating reStructuredText markup`_: ``python -m twine check dist/*`` 40 | 41 | .. _Validating reStructuredText markup: https://packaging.python.org/guides/making-a-pypi-friendly-readme/#validating-restructuredtext-markup 42 | 43 | Upload to Test PyPI 44 | =================== 45 | 46 | Set up the ``$HOME/.pypirc`` (Linux) or ``%UserProfile%\.pypirc`` (Windows) 47 | 48 | #. ``python -m twine upload --repository testpypi dist/*`` 49 | #. Check package uploaded properly: `TestPyPI PyExifTool`_ 50 | #. Create a temporary venv to test PyPI and run tests 51 | 52 | #. ``python -m venv tmp`` 53 | #. Activate venv 54 | #. ``python -m pip install -U -i https://test.pypi.org/simple/ PyExifTool`` 55 | 56 | * 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`` 57 | * If you want to test a specific version, can specify as ``PyExifTool==``, otherwise it installs the latest by default 58 | 59 | #. Make sure exiftool is found on PATH 60 | #. Run tests: ``python -m pytext -v `` 61 | 62 | #. Examine files installed to make sure it looks ok 63 | 64 | #. Cleanup: ``python -m pip uninstall PyExifTool``, then delete temp venv 65 | 66 | 67 | .. _`TestPyPI PyExifTool`: https://test.pypi.org/project/PyExifTool/#history 68 | 69 | Release 70 | ======= 71 | 72 | #. Be very sure all the tests pass and the package is good, because `PyPI does not allow for a filename to be reused`_ 73 | #. Release to production PyPI: ``python -m twine upload dist/*`` 74 | #. If needed, create a tag, and a GitHub release with the *whl* file 75 | 76 | .. code-block:: bash 77 | 78 | git tag -a vX.X.X 79 | git push --tags 80 | 81 | .. _PyPI does not allow for a filename to be reused: https://pypi.org/help/#file-name-reuse 82 | 83 | -------------------------------------------------------------------------------- /docs/source/package.rst: -------------------------------------------------------------------------------- 1 | **************** 2 | Package Overview 3 | **************** 4 | 5 | All classes live under the PyExifTool library namespace: ``exiftool`` 6 | 7 | Design 8 | ====== 9 | 10 | .. include:: ../../README.rst 11 | :start-after: DESIGN_INFO_START 12 | :end-before: DESIGN_INFO_END 13 | 14 | .. inheritance-diagram:: exiftool.ExifToolAlpha 15 | 16 | .. include:: ../../README.rst 17 | :start-after: DESIGN_CLASS_START 18 | :end-before: DESIGN_CLASS_END 19 | 20 | 21 | Fork Origins / Brief History 22 | ============================ 23 | 24 | .. include:: ../../README.rst 25 | :start-after: HISTORY_START 26 | :end-before: HISTORY_END 27 | 28 | 29 | License 30 | ======= 31 | 32 | .. include:: ../../README.rst 33 | :start-after: LICENSE_START 34 | :end-before: LICENSE_END 35 | -------------------------------------------------------------------------------- /docs/source/reference/1-exiftool.rst: -------------------------------------------------------------------------------- 1 | *********************** 2 | Class exiftool.ExifTool 3 | *********************** 4 | 5 | .. inheritance-diagram:: exiftool.ExifTool 6 | 7 | .. autoapimodule:: exiftool.ExifTool 8 | :members: 9 | :undoc-members: 10 | :special-members: __init__ 11 | :show-inheritance: 12 | 13 | .. :private-members: 14 | .. currently excluding private members 15 | -------------------------------------------------------------------------------- /docs/source/reference/2-helper.rst: -------------------------------------------------------------------------------- 1 | ***************************** 2 | Class exiftool.ExifToolHelper 3 | ***************************** 4 | 5 | .. inheritance-diagram:: exiftool.ExifToolHelper 6 | 7 | .. autoapimodule:: exiftool.ExifToolHelper 8 | :members: 9 | :undoc-members: 10 | :special-members: __init__ 11 | :show-inheritance: 12 | -------------------------------------------------------------------------------- /docs/source/reference/3-alpha.rst: -------------------------------------------------------------------------------- 1 | **************************** 2 | Class exiftool.ExifToolAlpha 3 | **************************** 4 | 5 | .. inheritance-diagram:: exiftool.ExifToolAlpha 6 | 7 | .. autoapimodule:: exiftool.ExifToolAlpha 8 | :members: 9 | :undoc-members: 10 | :special-members: __init__ 11 | :show-inheritance: 12 | -------------------------------------------------------------------------------- /exiftool/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is part of PyExifTool. 4 | # 5 | # PyExifTool 6 | # 7 | # Copyright 2019-2023 Kevin M (sylikc) 8 | # Copyright 2012-2014 Sven Marnach 9 | # 10 | # Community contributors are listed in the CHANGELOG.md for the PRs 11 | # 12 | # PyExifTool is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the licence, or 15 | # (at your option) any later version, or the BSD licence. 16 | # 17 | # PyExifTool is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 20 | # 21 | # See COPYING.GPL or COPYING.BSD for more details. 22 | 23 | """ 24 | PyExifTool is a Python library to communicate with an instance of Phil 25 | Harvey's excellent ExifTool_ command-line application. The library 26 | provides the class :py:class:`ExifTool` that runs the command-line 27 | tool in batch mode and features methods to send commands to that 28 | program, including methods to extract meta-information from one or 29 | more image files. Since ``exiftool`` is run in batch mode, only a 30 | single instance needs to be launched and can be reused for many 31 | queries. This is much more efficient than launching a separate 32 | process for every single query. 33 | 34 | .. _ExifTool: https://exiftool.org 35 | 36 | The source code can be checked out from the github repository with 37 | 38 | :: 39 | 40 | git clone git://github.com/sylikc/pyexiftool.git 41 | 42 | Alternatively, you can download a tarball_. There haven't been any 43 | releases yet. 44 | 45 | .. _tarball: https://github.com/sylikc/pyexiftool/tarball/master 46 | 47 | PyExifTool is licenced under GNU GPL version 3 or later, or BSD license. 48 | 49 | Example usage:: 50 | 51 | import exiftool 52 | 53 | files = ["a.jpg", "b.png", "c.tif"] 54 | with exiftool.ExifToolHelper() as et: 55 | metadata = et.get_metadata(files) 56 | for d in metadata: 57 | print("{:20.20} {:20.20}".format(d["SourceFile"], 58 | d["EXIF:DateTimeOriginal"])) 59 | 60 | """ 61 | 62 | # version number using Semantic Versioning 2.0.0 https://semver.org/ 63 | # may not be PEP-440 compliant https://www.python.org/dev/peps/pep-0440/#semantic-versioning 64 | __version__ = "0.5.6" 65 | 66 | 67 | # while we COULD import all the exceptions into the base library namespace, 68 | # it's best that it lives as exiftool.exceptions, to not pollute the base namespace 69 | from . import exceptions 70 | 71 | 72 | # make all of the original exiftool stuff available in this namespace 73 | from .exiftool import ExifTool 74 | from .helper import ExifToolHelper 75 | from .experimental import ExifToolAlpha 76 | 77 | # an old feature of the original class that exposed this variable at the library level 78 | # TODO may remove and deprecate at a later time 79 | #from .constants import DEFAULT_EXECUTABLE 80 | -------------------------------------------------------------------------------- /exiftool/constants.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is part of PyExifTool. 4 | # 5 | # PyExifTool 6 | # 7 | # Copyright 2019-2023 Kevin M (sylikc) 8 | # Copyright 2012-2014 Sven Marnach 9 | # 10 | # Community contributors are listed in the CHANGELOG.md for the PRs 11 | # 12 | # PyExifTool is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the licence, or 15 | # (at your option) any later version, or the BSD licence. 16 | # 17 | # PyExifTool is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 20 | # 21 | # See COPYING.GPL or COPYING.BSD for more details. 22 | 23 | """ 24 | 25 | This submodule defines constants which are used by other modules in the package 26 | 27 | """ 28 | 29 | import sys 30 | 31 | 32 | ################################## 33 | ############# HELPERS ############ 34 | ################################## 35 | 36 | # instead of comparing everywhere sys.platform, do it all here in the constants (less typo chances) 37 | # True if Windows 38 | PLATFORM_WINDOWS: bool = (sys.platform == 'win32') 39 | """sys.platform check, set to True if Windows""" 40 | 41 | # Prior to Python 3.3, the value for any Linux version is always linux2; after, it is linux. 42 | # https://stackoverflow.com/a/13874620/15384838 43 | PLATFORM_LINUX: bool = (sys.platform == 'linux' or sys.platform == 'linux2') 44 | """sys.platform check, set to True if Linux""" 45 | 46 | 47 | 48 | ################################## 49 | ####### PLATFORM DEFAULTS ######## 50 | ################################## 51 | 52 | 53 | # specify the extension so exiftool doesn't default to running "exiftool.py" on windows (which could happen) 54 | DEFAULT_EXECUTABLE: str = "exiftool.exe" if PLATFORM_WINDOWS else "exiftool" 55 | """The name of the default executable to run. 56 | 57 | ``exiftool.exe`` (Windows) or ``exiftool`` (Linux/Mac/non-Windows platforms) 58 | 59 | By default, the executable is searched for on one of the paths listed in the 60 | ``PATH`` environment variable. If it's not on the ``PATH``, a full path should be specified in the 61 | ``executable`` argument of the ExifTool constructor (:py:meth:`exiftool.ExifTool.__init__`). 62 | """ 63 | 64 | """ 65 | # flipped the if/else so that the sphinx documentation shows "exiftool" rather than "exiftool.exe" 66 | if not PLATFORM_WINDOWS: # pytest-cov:windows: no cover 67 | DEFAULT_EXECUTABLE = "exiftool" 68 | else: 69 | DEFAULT_EXECUTABLE = "exiftool.exe" 70 | """ 71 | 72 | 73 | ################################## 74 | ####### STARTUP CONSTANTS ######## 75 | ################################## 76 | 77 | # for Windows STARTUPINFO 78 | SW_FORCEMINIMIZE: int = 11 79 | """Windows ShowWindow constant from win32con 80 | 81 | Indicates the launched process window should start minimized 82 | """ 83 | 84 | # for Linux preexec_fn 85 | PR_SET_PDEATHSIG: int = 1 86 | """Extracted from linux/prctl.h 87 | 88 | Allows a kill signal to be sent to child processes when the parent unexpectedly dies 89 | """ 90 | 91 | 92 | 93 | ################################## 94 | ######## GLOBAL DEFAULTS ######### 95 | ################################## 96 | 97 | DEFAULT_BLOCK_SIZE: int = 4096 98 | """The default block size when reading from exiftool. The standard value 99 | should be fine, though other values might give better performance in 100 | some cases.""" 101 | 102 | EXIFTOOL_MINIMUM_VERSION: str = "12.15" 103 | """this is the minimum *exiftool* version required for current version of PyExifTool 104 | 105 | * 8.40 / 8.60 (production): implemented the -stay_open flag 106 | * 12.10 / 12.15 (production): implemented exit status on -echo4 107 | """ 108 | -------------------------------------------------------------------------------- /exiftool/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is part of PyExifTool. 4 | # 5 | # PyExifTool 6 | # 7 | # Copyright 2019-2023 Kevin M (sylikc) 8 | # Copyright 2012-2014 Sven Marnach 9 | # 10 | # Community contributors are listed in the CHANGELOG.md for the PRs 11 | # 12 | # PyExifTool is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the licence, or 15 | # (at your option) any later version, or the BSD licence. 16 | # 17 | # PyExifTool is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 20 | # 21 | # See COPYING.GPL or COPYING.BSD for more details. 22 | 23 | """ 24 | 25 | This submodule holds all of the custom exceptions which can be raised by PyExifTool 26 | 27 | """ 28 | 29 | 30 | ######################################################## 31 | #################### Base Exception #################### 32 | ######################################################## 33 | 34 | 35 | class ExifToolException(Exception): 36 | """ 37 | Generic Base class for all ExifTool error classes 38 | """ 39 | 40 | 41 | ############################################################# 42 | #################### Process State Error #################### 43 | ############################################################# 44 | 45 | 46 | class ExifToolProcessStateError(ExifToolException): 47 | """ 48 | Base class for all errors related to the invalid state of `exiftool` subprocess 49 | """ 50 | 51 | 52 | class ExifToolRunning(ExifToolProcessStateError): 53 | """ 54 | ExifTool is already running 55 | """ 56 | def __init__(self, message: str): 57 | super().__init__(f"ExifTool instance is running: {message}") 58 | 59 | 60 | class ExifToolNotRunning(ExifToolProcessStateError): 61 | """ 62 | ExifTool is not running 63 | """ 64 | def __init__(self, message: str): 65 | super().__init__(f"ExifTool instance not running: {message}") 66 | 67 | 68 | ########################################################### 69 | #################### Execute Exception #################### 70 | ########################################################### 71 | 72 | # all of these exceptions are related to something regarding execute 73 | 74 | class ExifToolExecuteException(ExifToolException): 75 | """ 76 | This is the base exception class for all execute() associated errors. 77 | 78 | This exception is never returned directly from any method, but provides common interface for subclassed errors. 79 | 80 | (mimics the signature of :py:class:`subprocess.CalledProcessError`) 81 | 82 | :attribute cmd: Parameters sent to *exiftool* which raised the error 83 | :attribute returncode: Exit Status (Return code) of the ``execute()`` command which raised the error 84 | :attribute stdout: STDOUT stream returned by the command which raised the error 85 | :attribute stderr: STDERR stream returned by the command which raised the error 86 | """ 87 | def __init__(self, message, exit_status, cmd_stdout, cmd_stderr, params): 88 | super().__init__(message) 89 | 90 | self.returncode: int = exit_status 91 | self.cmd: list = params 92 | self.stdout: str = cmd_stdout 93 | self.stderr: str = cmd_stderr 94 | 95 | 96 | class ExifToolExecuteError(ExifToolExecuteException): 97 | """ 98 | ExifTool executed the command but returned a non-zero exit status. 99 | 100 | .. note:: 101 | There is a similarly named :py:exc:`ExifToolExecuteException` which this Error inherits from. 102 | 103 | That is a base class and never returned directly. This is what is raised. 104 | """ 105 | def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): 106 | super().__init__(f"execute returned a non-zero exit status: {exit_status}", exit_status, cmd_stdout, cmd_stderr, params) 107 | 108 | 109 | ######################################################## 110 | #################### JSON Exception #################### 111 | ######################################################## 112 | 113 | 114 | class ExifToolOutputEmptyError(ExifToolExecuteException): 115 | """ 116 | ExifTool execute_json() expected output, but execute() did not return any output on stdout 117 | 118 | This is an error, because if you expect no output, don't use execute_json() 119 | 120 | .. note:: 121 | Only thrown by execute_json() 122 | """ 123 | def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): 124 | super().__init__("execute_json expected output on stdout but got none", exit_status, cmd_stdout, cmd_stderr, params) 125 | 126 | 127 | class ExifToolJSONInvalidError(ExifToolExecuteException): 128 | """ 129 | ExifTool execute_json() expected valid JSON to be returned, but got invalid JSON. 130 | 131 | This is an error, because if you expect non-JSON output, don't use execute_json() 132 | 133 | .. note:: 134 | Only thrown by execute_json() 135 | """ 136 | def __init__(self, exit_status, cmd_stdout, cmd_stderr, params): 137 | super().__init__("execute_json received invalid JSON output from exiftool", exit_status, cmd_stdout, cmd_stderr, params) 138 | 139 | 140 | ######################################################### 141 | #################### Other Exception #################### 142 | ######################################################### 143 | 144 | class ExifToolVersionError(ExifToolException): 145 | """ 146 | Generic Error to represent some version mismatch. 147 | 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 148 | """ 149 | 150 | 151 | class ExifToolTagNameError(ExifToolException): 152 | """ 153 | ExifToolHelper found an invalid tag name 154 | 155 | This error is raised when :py:attr:`exiftool.ExifToolHelper.check_tag_names` is enabled, and a bad tag is provided to a method 156 | """ 157 | def __init__(self, bad_tag): 158 | super().__init__(f"Invalid Tag Name found: \"{bad_tag}\"") 159 | -------------------------------------------------------------------------------- /exiftool/experimental.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is part of PyExifTool. 4 | # 5 | # PyExifTool 6 | # 7 | # Copyright 2019-2023 Kevin M (sylikc) 8 | # Copyright 2012-2014 Sven Marnach 9 | # 10 | # Community contributors are listed in the CHANGELOG.md for the PRs 11 | # 12 | # PyExifTool is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the licence, or 15 | # (at your option) any later version, or the BSD licence. 16 | # 17 | # PyExifTool is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 20 | # 21 | # See COPYING.GPL or COPYING.BSD for more details. 22 | 23 | 24 | """ 25 | This submodule contains the ``ExifToolAlpha`` class, which extends the ``ExifToolHelper`` class with experimental functionality. 26 | 27 | .. note:: 28 | :py:class:`exiftool.helper.ExifToolAlpha` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolAlpha` 29 | 30 | """ 31 | 32 | from pathlib import Path 33 | 34 | from .helper import ExifToolHelper 35 | 36 | 37 | try: # Py3k compatibility 38 | basestring 39 | except NameError: 40 | basestring = (bytes, str) 41 | 42 | # ====================================================================================================================== 43 | 44 | #def atexit_handler 45 | 46 | # constants related to keywords manipulations 47 | KW_TAGNAME = "IPTC:Keywords" 48 | KW_REPLACE, KW_ADD, KW_REMOVE = range(3) 49 | 50 | 51 | 52 | 53 | 54 | # ====================================================================================================================== 55 | 56 | 57 | 58 | #string helper 59 | def strip_nl(s): 60 | return ' '.join(s.splitlines()) 61 | 62 | # ====================================================================================================================== 63 | 64 | # Error checking function 65 | # very rudimentary checking 66 | # Note: They are quite fragile, because this just parses the output text from exiftool 67 | def check_ok(result): 68 | """Evaluates the output from a exiftool write operation (e.g. `set_tags`) 69 | 70 | The argument is the result from the execute method. 71 | 72 | The result is True or False. 73 | """ 74 | return not result is None and (not "due to errors" in result) 75 | 76 | # ====================================================================================================================== 77 | 78 | def format_error(result): 79 | """Evaluates the output from a exiftool write operation (e.g. `set_tags`) 80 | 81 | The argument is the result from the execute method. 82 | 83 | The result is a human readable one-line string. 84 | """ 85 | if check_ok(result): 86 | return f'exiftool probably finished properly. ("{strip_nl(result)}")' 87 | else: 88 | if result is None: 89 | return "exiftool operation can't be evaluated: No result given" 90 | else: 91 | return f'exiftool finished with error: "{strip_nl(result)}"' 92 | 93 | 94 | 95 | # ====================================================================================================================== 96 | 97 | class ExifToolAlpha(ExifToolHelper): 98 | """ 99 | This class is for the "experimental" functionality. In the grand scheme of things, this class 100 | contains "not well tested" functionality, methods that are less used, or methods with niche use cases. 101 | In some methods, edge cases on some of these methods may produce unexpected or ambiguous results. 102 | However, if there is increased demand, or robustness improves, functionality may merge into 103 | :py:class:`exiftool.ExifToolHelper` class. 104 | 105 | The starting point of this class was to remove all the "less used" functionality that was merged in 106 | on some arbitrary pull requests to the original v0.2 PyExifTool repository. This alpha-quality code is brittle and contains 107 | 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 108 | of the :py:class:`exiftool.ExifTool` class or the stable extended functionality of the :py:class:`exiftool.ExifToolHelper` class 109 | with unneeded bloat. 110 | 111 | The class heirarchy: ExifTool -> ExifToolHelper -> ExifToolAlpha 112 | 113 | * ExifTool - stable base class with CORE functionality 114 | * ExifToolHelper - user friendly class that extends the base class with general functionality not found in the core 115 | * ExifToolAlpha - alpha-quality code which extends the ExifToolHelper to add functionality that is niche, brittle, or not well tested 116 | 117 | Because of this heirarchy, you could always use/extend the :py:class:`exiftool.ExifToolAlpha` class to have all functionality, 118 | or at your discretion, use one of the more stable classes above. 119 | 120 | Please issue PR to this class to add functionality, even if not tested well. This class is for experimental code after all! 121 | """ 122 | 123 | # ---------------------------------------------------------------------------------------------------------------------- 124 | # i'm not sure if the verification works, but related to pull request (#11) 125 | def execute_json_wrapper(self, filenames, params=None, retry_on_error=True): 126 | # make sure the argument is a list and not a single string 127 | # which would lead to strange errors 128 | if isinstance(filenames, basestring): 129 | raise TypeError("The argument 'filenames' must be an iterable of strings") 130 | 131 | execute_params = [] 132 | 133 | if params: 134 | execute_params.extend(params) 135 | execute_params.extend(filenames) 136 | 137 | result = self.execute_json(execute_params) 138 | 139 | if result: 140 | try: 141 | ExifToolAlpha._check_result_filelist(filenames, result) 142 | except IOError as error: 143 | # Restart the exiftool child process in these cases since something is going wrong 144 | self.terminate() 145 | self.run() 146 | 147 | if retry_on_error: 148 | result = self.execute_json_filenames(filenames, params, retry_on_error=False) 149 | else: 150 | raise error 151 | else: 152 | # Reasons for exiftool to provide an empty result, could be e.g. file not found, etc. 153 | # What should we do in these cases? We don't have any information what went wrong, therefore 154 | # we just return empty dictionaries. 155 | result = [{} for _ in filenames] 156 | 157 | return result 158 | 159 | # ---------------------------------------------------------------------------------------------------------------------- 160 | # allows adding additional checks (#11) 161 | def get_metadata_batch_wrapper(self, filenames, params=None): 162 | return self.execute_json_wrapper(filenames=filenames, params=params) 163 | 164 | # ---------------------------------------------------------------------------------------------------------------------- 165 | # (#11) 166 | def get_metadata_wrapper(self, filename, params=None): 167 | return self.execute_json_wrapper(filenames=[filename], params=params)[0] 168 | 169 | # ---------------------------------------------------------------------------------------------------------------------- 170 | # (#11) 171 | def get_tags_batch_wrapper(self, tags, filenames, params=None): 172 | params = (params if params else []) + ["-" + t for t in tags] 173 | return self.execute_json_wrapper(filenames=filenames, params=params) 174 | 175 | # ---------------------------------------------------------------------------------------------------------------------- 176 | # (#11) 177 | def get_tags_wrapper(self, tags, filename, params=None): 178 | return self.get_tags_batch_wrapper(tags, [filename], params=params)[0] 179 | 180 | # ---------------------------------------------------------------------------------------------------------------------- 181 | # (#11) 182 | def get_tag_batch_wrapper(self, tag, filenames, params=None): 183 | data = self.get_tags_batch_wrapper([tag], filenames, params=params) 184 | result = [] 185 | for d in data: 186 | d.pop("SourceFile") 187 | result.append(next(iter(d.values()), None)) 188 | return result 189 | 190 | # ---------------------------------------------------------------------------------------------------------------------- 191 | # this was a method with good intentions by the original author, but returns some inconsistent results in some cases 192 | # 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 193 | # try calling get_tag_batch("*.mp4", "QuickTime") or "QuickTime:all" ... the expected results is a dictionary but a single tag is returned 194 | def get_tag_batch(self, filenames, tag): 195 | """Extract a single tag from the given files. 196 | 197 | The first argument is a single tag name, as usual in the 198 | format :. 199 | 200 | The second argument is an iterable of file names. 201 | 202 | The return value is a list of tag values or ``None`` for 203 | non-existent tags, in the same order as ``filenames``. 204 | """ 205 | data = self.get_tags(filenames, [tag]) 206 | result = [] 207 | for d in data: 208 | d.pop("SourceFile") 209 | result.append(next(iter(d.values()), None)) 210 | return result 211 | 212 | # ---------------------------------------------------------------------------------------------------------------------- 213 | # (#11) 214 | def get_tag_wrapper(self, tag, filename, params=None): 215 | return self.get_tag_batch_wrapper(tag, [filename], params=params)[0] 216 | 217 | # ---------------------------------------------------------------------------------------------------------------------- 218 | def get_tag(self, filename, tag): 219 | """ 220 | Extract a single tag from a single file. 221 | 222 | The return value is the value of the specified tag, or 223 | ``None`` if this tag was not found in the file. 224 | 225 | Does existence checks 226 | """ 227 | 228 | #return self.get_tag_batch([filename], tag)[0] 229 | 230 | p = Path(filename) 231 | 232 | if not p.exists(): 233 | raise FileNotFoundError 234 | 235 | data = self.get_tags(p, tag) 236 | if len(data) > 1: 237 | raise RuntimeError("one file requested but multiple returned?") 238 | 239 | d = data[0] 240 | d.pop("SourceFile") 241 | 242 | if len(d.values()) > 1: 243 | raise RuntimeError("multiple tag values returned, invalid use case") 244 | 245 | return next(iter(d.values()), None) 246 | 247 | 248 | 249 | # ---------------------------------------------------------------------------------------------------------------------- 250 | def copy_tags(self, from_filename, to_filename): 251 | """Copy all tags from one file to another.""" 252 | params = ["-overwrite_original", "-TagsFromFile", str(from_filename), str(to_filename)] 253 | self.execute(*params) 254 | 255 | # ---------------------------------------------------------------------------------------------------------------------- 256 | def set_keywords_batch(self, files, mode, keywords): 257 | """Modifies the keywords tag for the given files. 258 | 259 | The first argument is the operation mode: 260 | 261 | * KW_REPLACE: Replace (i.e. set) the full keywords tag with `keywords`. 262 | * KW_ADD: Add `keywords` to the keywords tag. 263 | If a keyword is present, just keep it. 264 | * KW_REMOVE: Remove `keywords` from the keywords tag. 265 | If a keyword wasn't present, just leave it. 266 | 267 | The second argument is an iterable of key words. 268 | 269 | The third argument is an iterable of file names. 270 | 271 | The format of the return value is the same as for 272 | :py:meth:`execute()`. 273 | 274 | It can be passed into `check_ok()` and `format_error()`. 275 | """ 276 | # Explicitly ruling out strings here because passing in a 277 | # string would lead to strange and hard-to-find errors 278 | if isinstance(keywords, basestring): 279 | raise TypeError("The argument 'keywords' must be " 280 | "an iterable of strings") 281 | 282 | # allow the files argument to be a str, and process it into a list of str 283 | filenames = self.__class__._parse_arg_files(files) 284 | 285 | params = [] 286 | 287 | kw_operation = {KW_REPLACE: "-%s=%s", 288 | KW_ADD: "-%s+=%s", 289 | KW_REMOVE: "-%s-=%s"}[mode] 290 | 291 | kw_params = [kw_operation % (KW_TAGNAME, w) for w in keywords] 292 | 293 | params.extend(kw_params) 294 | params.extend(filenames) 295 | if self._logger: self._logger.debug(params) 296 | 297 | return self.execute(*params) 298 | 299 | # ---------------------------------------------------------------------------------------------------------------------- 300 | def set_keywords(self, filename, mode, keywords): 301 | """Modifies the keywords tag for the given file. 302 | 303 | This is a convenience function derived from `set_keywords_batch()`. 304 | Only difference is that it takes as last argument only one file name 305 | as a string. 306 | """ 307 | return self.set_keywords_batch([filename], mode, keywords) 308 | 309 | 310 | # ---------------------------------------------------------------------------------------------------------------------- 311 | @staticmethod 312 | def _check_result_filelist(file_paths, result): 313 | """ 314 | Checks if the given file paths matches the 'SourceFile' entries in the result returned by 315 | exiftool. This is done to find possible mix ups in the streamed responses. 316 | """ 317 | # do some sanity checks on the results to make sure nothing was mixed up during reading from stdout 318 | if len(result) != len(file_paths): 319 | raise IOError(f"exiftool returned {len(result)} results, but expected was {len(file_paths)}") 320 | 321 | for i in range(len(file_paths)): 322 | returned_source_file = result[i].get('SourceFile') 323 | requested_file = file_paths[i] 324 | 325 | if returned_source_file != requested_file: 326 | raise IOError(f"exiftool returned data for file {returned_source_file}, but expected was {requested_file}") 327 | 328 | # ---------------------------------------------------------------------------------------------------------------------- 329 | -------------------------------------------------------------------------------- /exiftool/helper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is part of PyExifTool. 4 | # 5 | # PyExifTool 6 | # 7 | # Copyright 2019-2023 Kevin M (sylikc) 8 | # Copyright 2012-2014 Sven Marnach 9 | # 10 | # Community contributors are listed in the CHANGELOG.md for the PRs 11 | # 12 | # PyExifTool is free software: you can redistribute it and/or modify 13 | # it under the terms of the GNU General Public License as published by 14 | # the Free Software Foundation, either version 3 of the licence, or 15 | # (at your option) any later version, or the BSD licence. 16 | # 17 | # PyExifTool is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 20 | # 21 | # See COPYING.GPL or COPYING.BSD for more details. 22 | 23 | 24 | """ 25 | This submodule contains the ``ExifToolHelper`` class, which makes the core ``ExifTool`` class easier, and safer to use. 26 | 27 | .. note:: 28 | :py:class:`exiftool.helper.ExifToolHelper` class of this submodule is available in the ``exiftool`` namespace as :py:class:`exiftool.ExifToolHelper` 29 | 30 | """ 31 | 32 | import re 33 | 34 | from .exiftool import ExifTool 35 | from .exceptions import ExifToolOutputEmptyError, ExifToolJSONInvalidError, ExifToolExecuteError, ExifToolTagNameError 36 | 37 | # basestring makes no sense in Python 3, so renamed tuple to this const 38 | TUPLE_STR_BYTES: tuple = (str, bytes,) 39 | 40 | from typing import Any, Union, Optional, List, Dict 41 | 42 | 43 | 44 | 45 | # ====================================================================================================================== 46 | 47 | 48 | def _is_iterable(in_param: Any, ignore_str_bytes: bool = False) -> bool: 49 | """ 50 | Checks if this item is iterable, instead of using isinstance(list), anything iterable can be ok 51 | 52 | .. note:: 53 | STRINGS ARE CONSIDERED ITERABLE by Python 54 | 55 | if you need to consider a code path for strings first, check that before checking if a parameter is iterable via this function 56 | 57 | or specify ``ignore_str_bytes=True`` 58 | 59 | :param in_param: Something to check if iterable or not 60 | :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 61 | """ 62 | 63 | if ignore_str_bytes and isinstance(in_param, TUPLE_STR_BYTES): 64 | return False 65 | 66 | # a different type of test of iterability, instead of using isinstance(list) 67 | # https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable 68 | try: 69 | iterator = iter(in_param) 70 | except TypeError: 71 | return False 72 | 73 | return True 74 | 75 | 76 | 77 | # ====================================================================================================================== 78 | 79 | class ExifToolHelper(ExifTool): 80 | """ 81 | This class extends the low-level :py:class:`exiftool.ExifTool` class with 'wrapper'/'helper' functionality 82 | 83 | It keeps low-level core functionality with the base class but extends helper functions in a separate class 84 | """ 85 | 86 | ########################################################################################## 87 | #################################### OVERRIDE METHODS #################################### 88 | ########################################################################################## 89 | 90 | # ---------------------------------------------------------------------------------------------------------------------- 91 | def __init__(self, auto_start: bool = True, check_execute: bool = True, check_tag_names: bool = True, **kwargs) -> None: 92 | """ 93 | :param bool auto_start: Will automatically start the exiftool process on first command run, defaults to True 94 | :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. 95 | :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. 96 | 97 | :param kwargs: All other parameters are passed directly to the super-class constructor: :py:meth:`exiftool.ExifTool.__init__()` 98 | """ 99 | # call parent's constructor 100 | super().__init__(**kwargs) 101 | 102 | self._auto_start: bool = auto_start 103 | self._check_execute: bool = check_execute 104 | self._check_tag_names: bool = check_tag_names 105 | 106 | 107 | # ---------------------------------------------------------------------------------------------------------------------- 108 | def execute(self, *params: Any, **kwargs) -> Union[str, bytes]: 109 | """ 110 | Override the :py:meth:`exiftool.ExifTool.execute()` method 111 | 112 | Adds logic to auto-start if not running, if :py:attr:`auto_start` == True 113 | 114 | 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.) 115 | 116 | :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero 117 | """ 118 | if self._auto_start and not self.running: 119 | self.run() 120 | 121 | # by default, any non-(str/bytes) would throw a TypeError from ExifTool.execute(), so they're casted to a string here 122 | # 123 | # duck-type any given object to string 124 | # this was originally to support Path() but it's now generic enough to support any object that str() to something useful 125 | # 126 | # Thanks @jangop for the single line contribution! 127 | str_bytes_params: Union[str, bytes] = [x if isinstance(x, TUPLE_STR_BYTES) else str(x) for x in params] 128 | # 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? 129 | 130 | 131 | result: Union[str, bytes] = super().execute(*str_bytes_params, **kwargs) 132 | 133 | # imitate the subprocess.run() signature. check=True will check non-zero exit status 134 | if self._check_execute and self._last_status: 135 | raise ExifToolExecuteError(self._last_status, self._last_stdout, self._last_stderr, str_bytes_params) 136 | 137 | return result 138 | 139 | # ---------------------------------------------------------------------------------------------------------------------- 140 | def run(self) -> None: 141 | """ 142 | override the :py:meth:`exiftool.ExifTool.run()` method 143 | 144 | Will not attempt to run if already running (so no warning about 'ExifTool already running' will trigger) 145 | """ 146 | if self.running: 147 | return 148 | 149 | super().run() 150 | 151 | 152 | # ---------------------------------------------------------------------------------------------------------------------- 153 | def terminate(self, **opts) -> None: 154 | """ 155 | Overrides the :py:meth:`exiftool.ExifTool.terminate()` method. 156 | 157 | Will not attempt to terminate if not running (so no warning about 'ExifTool not running' will trigger) 158 | 159 | :param opts: passed directly to the parent call :py:meth:`exiftool.ExifTool.terminate()` 160 | """ 161 | if not self.running: 162 | return 163 | 164 | super().terminate(**opts) 165 | 166 | 167 | ######################################################################################## 168 | #################################### NEW PROPERTIES #################################### 169 | ######################################################################################## 170 | 171 | # ---------------------------------------------------------------------------------------------------------------------- 172 | @property 173 | def auto_start(self) -> bool: 174 | """ 175 | Read-only property. Gets the current setting passed into the constructor as to whether auto_start is enabled or not. 176 | 177 | (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.) 178 | """ 179 | return self._auto_start 180 | 181 | 182 | 183 | # ---------------------------------------------------------------------------------------------------------------------- 184 | @property 185 | def check_execute(self) -> bool: 186 | """ 187 | Flag to enable/disable checking exit status (return code) on execute 188 | 189 | If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolExecuteError` if a non-zero exit status is returned during :py:meth:`execute()` 190 | 191 | .. warning:: 192 | While this property is provided to give callers an option to enable/disable error checking, it is generally **NOT** recommended to disable ``check_execute``. 193 | 194 | **If disabled, exiftool will fail silently, and hard-to-catch bugs may arise.** 195 | 196 | 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) 197 | 198 | :getter: Returns current setting 199 | :setter: Enable or Disable the check 200 | 201 | .. note:: 202 | This settings can be changed any time and will only affect subsequent calls 203 | 204 | :type: bool 205 | """ 206 | return self._check_execute 207 | 208 | @check_execute.setter 209 | def check_execute(self, new_setting: bool) -> None: 210 | self._check_execute = new_setting 211 | 212 | 213 | # ---------------------------------------------------------------------------------------------------------------------- 214 | @property 215 | def check_tag_names(self) -> bool: 216 | """ 217 | Flag to enable/disable checking of tag names 218 | 219 | If enabled, will raise :py:exc:`exiftool.exceptions.ExifToolTagNameError` if an invalid tag name is detected. 220 | 221 | .. warning:: 222 | ExifToolHelper only checks the validity of the Tag **NAME** based on a simple regex pattern. 223 | 224 | * It *does not* validate whether the tag name is actually valid on the file type(s) you're accessing. 225 | * It *does not* validate whether the tag you passed in that "looks like" a tag is actually an option 226 | * It does support a "#" at the end of the tag name to disable print conversion 227 | 228 | Please refer to `ExifTool Tag Names`_ documentation for a complete list of valid tags recognized by ExifTool. 229 | 230 | .. warning:: 231 | 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``. 232 | 233 | **If disabled, you could accidentally edit a file when you meant to read it.** 234 | 235 | 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! 236 | 237 | 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`_!). 238 | 239 | :getter: Returns current setting 240 | :setter: Enable or Disable the check 241 | 242 | .. note:: 243 | This settings can be changed any time and will only affect subsequent calls 244 | 245 | :type: bool 246 | 247 | 248 | .. _file an issue: https://github.com/sylikc/pyexiftool/issues 249 | .. _ExifTool Tag Names: https://exiftool.org/TagNames/ 250 | """ 251 | return self._check_tag_names 252 | 253 | @check_tag_names.setter 254 | def check_tag_names(self, new_setting: bool) -> None: 255 | self._check_tag_names = new_setting 256 | 257 | 258 | # ---------------------------------------------------------------------------------------------------------------------- 259 | 260 | 261 | 262 | 263 | 264 | 265 | ##################################################################################### 266 | #################################### NEW METHODS #################################### 267 | ##################################################################################### 268 | 269 | 270 | # all generic helper functions will follow a convention of 271 | # function(files to be worked on, ... , params=) 272 | 273 | 274 | # ---------------------------------------------------------------------------------------------------------------------- 275 | def get_metadata(self, files: Union[str, List], params: Optional[Union[str, List]] = None) -> List: 276 | """ 277 | Return all metadata for the given files. 278 | 279 | .. note:: 280 | 281 | This is a convenience method. 282 | 283 | The implementation calls :py:meth:`get_tags()` with ``tags=None`` 284 | 285 | :param files: Files parameter matches :py:meth:`get_tags()` 286 | 287 | :param params: Optional parameters to send to *exiftool* 288 | :type params: list or None 289 | 290 | :return: The return value will have the format described in the documentation of :py:meth:`get_tags()`. 291 | """ 292 | return self.get_tags(files, None, params=params) 293 | 294 | 295 | # ---------------------------------------------------------------------------------------------------------------------- 296 | def get_tags(self, files: Union[Any, List[Any]], tags: Optional[Union[str, List]], params: Optional[Union[str, List]] = None) -> List: 297 | """ 298 | Return only specified tags for the given files. 299 | 300 | :param files: File(s) to be worked on. 301 | 302 | * If a non-iterable is provided, it will get tags for a single item (str(non-iterable)) 303 | * If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim. 304 | 305 | .. note:: 306 | Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`. 307 | 308 | .. warning:: 309 | Currently, filenames are NOT checked for existence! That is left up to the caller. 310 | 311 | .. warning:: 312 | Wildcard strings are valid and passed verbatim to exiftool. 313 | 314 | However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing, 315 | which may cause unexpected behavior if you're using one and comparing the result to the other. 316 | Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info. 317 | 318 | :type files: Any or List(Any) - see Note 319 | 320 | 321 | :param tags: Tag(s) to read. If tags is None, or [], method will returns all tags 322 | 323 | .. note:: 324 | The tag names may include group names, as usual in the format ``:``. 325 | 326 | :type tags: str, list, or None 327 | 328 | 329 | :param params: Optional parameter(s) to send to *exiftool* 330 | :type params: Any, List[Any], or None 331 | 332 | 333 | :return: The format of the return value is the same as for :py:meth:`exiftool.ExifTool.execute_json()`. 334 | 335 | 336 | :raises ValueError: Invalid Parameter 337 | :raises TypeError: Invalid Parameter 338 | :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero 339 | 340 | 341 | .. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2 342 | 343 | """ 344 | 345 | final_tags: Optional[List] = None 346 | final_files: List = self.__class__._parse_arg_files(files) 347 | 348 | if tags is None: 349 | # all tags 350 | final_tags = [] 351 | elif isinstance(tags, TUPLE_STR_BYTES): 352 | final_tags = [tags] 353 | elif _is_iterable(tags): 354 | final_tags = tags 355 | else: 356 | raise TypeError(f"{self.__class__.__name__}.get_tags: argument 'tags' must be a str/bytes or a list") 357 | 358 | if self._check_tag_names: 359 | # run check if enabled 360 | self.__class__._check_tag_list(final_tags) 361 | 362 | exec_params: List = [] 363 | 364 | # we extend an empty list to avoid modifying any referenced inputs 365 | if params: 366 | if _is_iterable(params, ignore_str_bytes=True): 367 | exec_params.extend(params) 368 | else: 369 | exec_params.append(params) 370 | 371 | # tags is always a list by this point. It will always be iterable... don't have to check for None 372 | exec_params.extend([f"-{t}" for t in final_tags]) 373 | 374 | exec_params.extend(final_files) 375 | 376 | try: 377 | ret = self.execute_json(*exec_params) 378 | except ExifToolOutputEmptyError: 379 | raise 380 | #raise RuntimeError(f"{self.__class__.__name__}.get_tags: exiftool returned no data") 381 | except ExifToolJSONInvalidError: 382 | raise 383 | except ExifToolExecuteError: 384 | # if last_status is <> 0, raise an error that one or more files failed? 385 | raise 386 | 387 | return ret 388 | 389 | 390 | # ---------------------------------------------------------------------------------------------------------------------- 391 | def set_tags(self, files: Union[Any, List[Any]], tags: Dict, params: Optional[Union[str, List]] = None): 392 | """ 393 | Writes the values of the specified tags for the given file(s). 394 | 395 | :param files: File(s) to be worked on. 396 | 397 | * If a non-iterable is provided, it will get tags for a single item (str(non-iterable)) 398 | * If an iterable is provided, the list is passed into :py:meth:`execute_json` verbatim. 399 | 400 | .. note:: 401 | Any files/params which are not bytes/str will be casted to a str in :py:meth:`execute()`. 402 | 403 | .. warning:: 404 | Currently, filenames are NOT checked for existence! That is left up to the caller. 405 | 406 | .. warning:: 407 | Wildcard strings are valid and passed verbatim to exiftool. 408 | 409 | However, exiftool's wildcard matching/globbing may be different than Python's matching/globbing, 410 | which may cause unexpected behavior if you're using one and comparing the result to the other. 411 | Read `ExifTool Common Mistakes - Over-use of Wildcards in File Names`_ for some related info. 412 | 413 | :type files: Any or List(Any) - see Note 414 | 415 | 416 | :param tags: Tag(s) to write. 417 | 418 | Dictionary keys = tags, values = tag values (str or list) 419 | 420 | * If a value is a str, will set key=value 421 | * If a value is a list, will iterate over list and set each individual value to the same tag ( 422 | 423 | .. note:: 424 | The tag names may include group names, as usual in the format ``:``. 425 | 426 | .. note:: 427 | 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 428 | 429 | This allows setting things like ``-Keywords=a -Keywords=b -Keywords=c`` by passing in ``tags={"Keywords": ['a', 'b', 'c']}`` 430 | 431 | :type tags: dict 432 | 433 | 434 | :param params: Optional parameter(s) to send to *exiftool* 435 | :type params: str, list, or None 436 | 437 | 438 | :return: The format of the return value is the same as for :py:meth:`execute()`. 439 | 440 | 441 | :raises ValueError: Invalid Parameter 442 | :raises TypeError: Invalid Parameter 443 | :raises ExifToolExecuteError: If :py:attr:`check_execute` == True, and exit status was non-zero 444 | 445 | 446 | .. _ExifTool Common Mistakes - Over-use of Wildcards in File Names: https://exiftool.org/mistakes.html#M2 447 | 448 | """ 449 | final_files: List = self.__class__._parse_arg_files(files) 450 | 451 | if not tags: 452 | raise ValueError(f"{self.__class__.__name__}.set_tags: argument 'tags' cannot be empty") 453 | elif not isinstance(tags, dict): 454 | raise TypeError(f"{self.__class__.__name__}.set_tags: argument 'tags' must be a dict") 455 | 456 | 457 | if self._check_tag_names: 458 | # run check if enabled 459 | self.__class__._check_tag_list(list(tags)) # gets only the keys (tag names) 460 | 461 | exec_params: List = [] 462 | 463 | # we extend an empty list to avoid modifying any referenced inputs 464 | if params: 465 | if _is_iterable(params, ignore_str_bytes=True): 466 | exec_params.extend(params) 467 | else: 468 | exec_params.append(params) 469 | 470 | for tag, value in tags.items(): 471 | # contributed by @daviddorme in https://github.com/sylikc/pyexiftool/issues/12#issuecomment-821879234 472 | # allows setting things like Keywords which require separate directives 473 | # > exiftool -Keywords=keyword1 -Keywords=keyword2 -Keywords=keyword3 file.jpg 474 | # which are not supported as duplicate keys in a dictionary 475 | if isinstance(value, list): 476 | for item in value: 477 | exec_params.append(f"-{tag}={item}") 478 | else: 479 | exec_params.append(f"-{tag}={value}") 480 | 481 | exec_params.extend(final_files) 482 | 483 | try: 484 | return self.execute(*exec_params) 485 | #TODO if execute returns data, then error? 486 | except ExifToolExecuteError: 487 | # last status non-zero 488 | raise 489 | 490 | 491 | # ---------------------------------------------------------------------------------------------------------------------- 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | ######################################################################################### 500 | #################################### PRIVATE METHODS #################################### 501 | ######################################################################################### 502 | 503 | 504 | 505 | # ---------------------------------------------------------------------------------------------------------------------- 506 | @staticmethod 507 | def _parse_arg_files(files: Union[str, List]) -> List: 508 | """ 509 | This logic to process the files argument is common across most ExifToolHelper methods 510 | 511 | It can be used by a developer to process the files argument the same way if this class is extended 512 | 513 | :param files: File(s) to be worked on. 514 | :type files: str or list 515 | 516 | :return: A list of one or more elements containing strings of files 517 | 518 | :raises ValueError: Files parameter is empty 519 | """ 520 | 521 | final_files: List = [] 522 | 523 | if not files: 524 | # Exiftool process would return an error anyways 525 | raise ValueError("ERROR: Argument 'files' cannot be empty") 526 | elif not _is_iterable(files, ignore_str_bytes=True): 527 | # if it's not a string but also not iterable 528 | final_files = [files] 529 | else: 530 | final_files = files 531 | 532 | 533 | return final_files 534 | 535 | 536 | # ---------------------------------------------------------------------------------------------------------------------- 537 | @staticmethod 538 | def _check_tag_list(tags: List) -> None: 539 | """ 540 | Private method. This method is used to check the validity of a tag list passed in. 541 | 542 | 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. 543 | 544 | :param list tags: List of tags to check 545 | 546 | :return: None if checks passed. Raises an error otherwise. (Think of it like an assert statement) 547 | """ 548 | # In the future if a specific version changed the match pattern, 549 | # we can check self.version ... then this method will no longer 550 | # be static and requires the underlying exiftool process to be running to get the self.version 551 | # 552 | # This is not done right now because the odds of the tag name format changing is very low, and requiring 553 | # exiftool to be running during this tag check could introduce unneccesary overhead at this time 554 | 555 | 556 | 557 | # According to the exiftool source code, the valid regex on tags is (/^([-\w*]+:)*([-\w*?]+)#?$/) 558 | # However, it appears that "-" may be allowed within a tag name/group (i.e. https://exiftool.org/TagNames/XMP.html Description tags) 559 | # 560 | # \w in Perl => https://perldoc.perl.org/perlrecharclass#Backslash-sequences 561 | # \w in Python => https://docs.python.org/3/library/re.html#regular-expression-syntax 562 | # 563 | # Perl vs Python's "\w" seem to mean slightly different things, so we write our own regex / matching algorithm 564 | 565 | 566 | # * make sure the first character is not a special one 567 | # * "#" can only appear at the end 568 | # * 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. 569 | # * *wildcard* tags are permitted by exiftool 570 | tag_regex = r"[\w\*][\w\:\-\*]*(#|)" 571 | 572 | for t in tags: 573 | if re.fullmatch(tag_regex, t) is None: 574 | raise ExifToolTagNameError(t) 575 | 576 | # returns nothing, if no error was raised, the tags passed 577 | 578 | # considering making this... 579 | # * can't begin with - 580 | # * can't have "=" anywhere, and that's it... 581 | # there's a lot of variations which might make this code buggy for some edge use cases 582 | 583 | 584 | 585 | # ---------------------------------------------------------------------------------------------------------------------- 586 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | ;[mypy-json.*] 2 | ;ignore_no_redef = True 3 | -------------------------------------------------------------------------------- /scripts/README.txt: -------------------------------------------------------------------------------- 1 | These are standardized scripts/batch files which run tests, code reviews, or other maintenance tasks in a repeatable way. 2 | 3 | 4 | While scripts could automatically install requirements, it is left up to the caller: 5 | 6 |