tiffcomment.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. # tifffile/tiffcomment.py
  3. """Print or replace ImageDescription in first page of TIFF file.
  4. Usage: ``tiffcomment [--set comment] file``
  5. """
  6. from __future__ import annotations
  7. import os
  8. import sys
  9. try:
  10. from .tifffile import tiffcomment
  11. except ImportError:
  12. try:
  13. from tifffile.tifffile import tiffcomment
  14. except ImportError:
  15. from tifffile import tiffcomment # noqa: PLW0406
  16. def main(argv: list[str] | None = None) -> int:
  17. """Tiffcomment command line usage main function."""
  18. comment: str | bytes | None
  19. if argv is None:
  20. argv = sys.argv
  21. if len(argv) > 2 and argv[1] in '--set':
  22. comment = argv[2]
  23. files = argv[3:]
  24. else:
  25. comment = None
  26. files = argv[1:]
  27. if len(files) == 0 or any(f.startswith('-') for f in files):
  28. print()
  29. print(__doc__.strip())
  30. return 0
  31. if comment is None:
  32. pass
  33. elif os.path.exists(comment):
  34. with open(comment, 'rb') as fh:
  35. comment = fh.read()
  36. else:
  37. try:
  38. comment = comment.encode('ascii')
  39. except UnicodeEncodeError as exc:
  40. print(f'{exc}')
  41. assert isinstance(comment, str)
  42. comment = comment.encode()
  43. for file in files:
  44. try:
  45. result = tiffcomment(file, comment)
  46. except Exception as exc:
  47. print(f'{file}: {exc}')
  48. else:
  49. if result:
  50. print(result)
  51. return 0
  52. if __name__ == '__main__':
  53. sys.exit(main())