From 60b4f88f17c275833540a94821e39caf539f367e Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 6 Feb 2015 10:58:07 -0800 Subject: [PATCH] Use logging instead of print. cf. #1191. Only TiffImagePlugin and OLEFileIO still rely on a DEBUG flag. I left TiffImagePlugin as it is because I hope #1059 gets merged in first, and OLEFileIO because it uses its own logic. Untested, as usual. --- PIL/Image.py | 20 +++++++------------- PIL/ImageFile.py | 24 ++++++++---------------- PIL/PcxImagePlugin.py | 19 +++++++++---------- PIL/PngImagePlugin.py | 16 ++++++++-------- PIL/PyAccess.py | 17 +++++++++-------- Scripts/pilfile.py | 10 ++++++++-- Scripts/player.py | 3 --- Tests/test_file_libtiff.py | 16 ++++++---------- Tests/test_file_tiff.py | 15 ++++++--------- Tests/test_imagesequence.py | 3 --- 10 files changed, 61 insertions(+), 82 deletions(-) diff --git a/PIL/Image.py b/PIL/Image.py index 7cfa72e6f..0ec1b1a8e 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -28,8 +28,11 @@ from __future__ import print_function from PIL import VERSION, PILLOW_VERSION, _plugins +import logging import warnings +logger = logging.getLogger(__name__) + class DecompressionBombWarning(RuntimeWarning): pass @@ -138,11 +141,6 @@ def isImageType(t): """ return hasattr(t, "im") -# -# Debug level - -DEBUG = 0 - # # Constants (also defined in _imagingmodule.c!) @@ -386,13 +384,10 @@ def init(): for plugin in _plugins: try: - if DEBUG: - print ("Importing %s" % plugin) + logger.debug("Importing %s", plugin) __import__("PIL.%s" % plugin, globals(), locals(), []) - except ImportError: - if DEBUG: - print("Image: failed to import", end=' ') - print(plugin, ":", sys.exc_info()[1]) + except ImportError as e: + logger.debug("Image: failed to import %s: %s", plugin, e) if OPEN or SAVE: _initialized = 2 @@ -545,8 +540,7 @@ class Image: try: self.fp.close() except Exception as msg: - if DEBUG: - print ("Error closing: %s" % msg) + logger.debug("Error closing: %s" % msg) # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image diff --git a/PIL/ImageFile.py b/PIL/ImageFile.py index 79faff797..4904a5f7d 100644 --- a/PIL/ImageFile.py +++ b/PIL/ImageFile.py @@ -30,10 +30,13 @@ from PIL import Image from PIL._util import isPath import io +import logging import os import sys import traceback +logger = logging.getLogger(__name__) + MAXBLOCK = 65536 SAFEBLOCK = 1024*1024 @@ -95,22 +98,11 @@ class ImageFile(Image.Image): try: self._open() - except IndexError as v: # end of data - if Image.DEBUG > 1: - traceback.print_exc() - raise SyntaxError(v) - except TypeError as v: # end of data (ord) - if Image.DEBUG > 1: - traceback.print_exc() - raise SyntaxError(v) - except KeyError as v: # unsupported mode - if Image.DEBUG > 1: - traceback.print_exc() - raise SyntaxError(v) - except EOFError as v: # got header but not the first frame - if Image.DEBUG > 1: - traceback.print_exc() - raise SyntaxError(v) + except (IndexError, # end of data + TypeError, # end of data (ord) + KeyError, # unsupported mode + EOFError) as v: # got header but not the first frame + logger.exception("%s") if not self.mode or self.size[0] <= 0: raise SyntaxError("not identified by this driver") diff --git a/PIL/PcxImagePlugin.py b/PIL/PcxImagePlugin.py index 0765f099e..6218a7e57 100644 --- a/PIL/PcxImagePlugin.py +++ b/PIL/PcxImagePlugin.py @@ -27,8 +27,11 @@ __version__ = "0.6" +import logging from PIL import Image, ImageFile, ImagePalette, _binary +logger = logging.getLogger(__name__) + i8 = _binary.i8 i16 = _binary.i16le o8 = _binary.o8 @@ -57,17 +60,15 @@ class PcxImageFile(ImageFile.ImageFile): bbox = i16(s, 4), i16(s, 6), i16(s, 8)+1, i16(s, 10)+1 if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: raise SyntaxError("bad PCX image size") - if Image.DEBUG: - print ("BBox: %s %s %s %s" % bbox) + logger.debug("BBox: %s %s %s %s", *bbox) # format version = i8(s[1]) bits = i8(s[3]) planes = i8(s[65]) stride = i16(s, 66) - if Image.DEBUG: - print ("PCX version %s, bits %s, planes %s, stride %s" % - (version, bits, planes, stride)) + logger.debug("PCX version %s, bits %s, planes %s, stride %s", + version, bits, planes, stride) self.info["dpi"] = i16(s, 12), i16(s, 14) @@ -105,8 +106,7 @@ class PcxImageFile(ImageFile.ImageFile): self.size = bbox[2]-bbox[0], bbox[3]-bbox[1] bbox = (0, 0) + self.size - if Image.DEBUG: - print ("size: %sx%s" % self.size) + logger.debug("size: %sx%s", *self.size) self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] @@ -142,9 +142,8 @@ def _save(im, fp, filename, check=0): # Ideally it should be passed in in the state, but the bytes value # gets overwritten. - if Image.DEBUG: - print ("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d" % ( - im.size[0], bits, stride)) + logger.debug("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d", + im.size[0], bits, stride)) # under windows, we could determine the current screen size with # "Image.core.display_mode()[1]", but I think that's overkill... diff --git a/PIL/PngImagePlugin.py b/PIL/PngImagePlugin.py index d8593f90d..33b89e6bd 100644 --- a/PIL/PngImagePlugin.py +++ b/PIL/PngImagePlugin.py @@ -35,10 +35,13 @@ from __future__ import print_function __version__ = "0.9" +import logging import re +import zlib from PIL import Image, ImageFile, ImagePalette, _binary -import zlib + +logger = logging.getLogger(__name__) i8 = _binary.i8 i16 = _binary.i16be @@ -127,8 +130,7 @@ class ChunkStream: def call(self, cid, pos, length): "Call the appropriate chunk handler" - if Image.DEBUG: - print("STREAM", cid, pos, length) + logger.debug("STREAM %s %s %s", cid, pos, length) return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length) def crc(self, cid, data): @@ -291,9 +293,8 @@ class PngStream(ChunkStream): # Compression method 1 byte (0) # Compressed profile n bytes (zlib with deflate compression) i = s.find(b"\0") - if Image.DEBUG: - print("iCCP profile name", s[:i]) - print("Compression method", i8(s[i])) + logger.debug("iCCP profile name %s", s[:i]) + logger.debug("Compression method %s", i8(s[i])) comp_method = i8(s[i]) if comp_method != 0: raise SyntaxError("Unknown compression method %s in iCCP chunk" % @@ -503,8 +504,7 @@ class PngImageFile(ImageFile.ImageFile): except EOFError: break except AttributeError: - if Image.DEBUG: - print(cid, pos, length, "(unknown)") + logger.debug("%s %s %s (unknown)", cid, pos, length) s = ImageFile._safe_read(self.fp, length) self.png.crc(cid, s) diff --git a/PIL/PyAccess.py b/PIL/PyAccess.py index a3f1c3909..d5ac238df 100644 --- a/PIL/PyAccess.py +++ b/PIL/PyAccess.py @@ -22,10 +22,14 @@ from __future__ import print_function -from cffi import FFI +import logging import sys -DEBUG = 0 +from cffi import FFI + + +logger = logging.getLogger(__name__) + defs = """ struct Pixel_RGBA { @@ -50,8 +54,7 @@ class PyAccess(object): self.xsize = vals['xsize'] self.ysize = vals['ysize'] - if DEBUG: - print (vals) + logger.debug("%s", vals) self._post_init() def _post_init(self): @@ -305,11 +308,9 @@ else: def new(img, readonly=False): access_type = mode_map.get(img.mode, None) if not access_type: - if DEBUG: - print("PyAccess Not Implemented: %s" % img.mode) + logger.debug("PyAccess Not Implemented: %s", img.mode) return None - if DEBUG: - print("New PyAccess: %s" % img.mode) + logger.debug("New PyAccess: %s", img.mode) return access_type(img, readonly) # End of file diff --git a/Scripts/pilfile.py b/Scripts/pilfile.py index 1b77b0e78..d0b145b4c 100644 --- a/Scripts/pilfile.py +++ b/Scripts/pilfile.py @@ -19,8 +19,11 @@ from __future__ import print_function +import getopt +import glob +import logging import site -import getopt, glob, sys +import sys from PIL import Image @@ -41,6 +44,7 @@ except getopt.error as v: sys.exit(1) verbose = quiet = verify = 0 +logging_level = "WARNING" for o, a in opt: if o == "-f": @@ -57,7 +61,9 @@ for o, a in opt: elif o == "-v": verify = 1 elif o == "-D": - Image.DEBUG += 1 + logging_level = "DEBUG" + +logging.basicConfig(level=logging_level) def globfix(files): # expand wildcards where necessary diff --git a/Scripts/player.py b/Scripts/player.py index 0c90286c5..e798c7752 100644 --- a/Scripts/player.py +++ b/Scripts/player.py @@ -15,9 +15,6 @@ from PIL import Image, ImageTk import sys -Image.DEBUG = 0 - - # -------------------------------------------------------------------- # an image animation player diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index a9377bf63..ab2ee037a 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -1,10 +1,13 @@ from helper import unittest, PillowTestCase, hopper, py3 -import os import io +import logging +import os from PIL import Image, TiffImagePlugin +logger = logging.getLogger(__name__) + class LibTiffTestCase(PillowTestCase): @@ -230,7 +233,6 @@ class TestFileLibTiff(LibTiffTestCase): """ Are we generating the same interpretation of the image as Imagemagick is? """ TiffImagePlugin.READ_LIBTIFF = True - # Image.DEBUG = True im = Image.open('Tests/images/12bit.cropped.tif') im.load() TiffImagePlugin.READ_LIBTIFF = False @@ -242,14 +244,8 @@ class TestFileLibTiff(LibTiffTestCase): im2 = Image.open('Tests/images/12in16bit.tif') - if Image.DEBUG: - print (im.getpixel((0, 0))) - print (im.getpixel((0, 1))) - print (im.getpixel((0, 2))) - - print (im2.getpixel((0, 0))) - print (im2.getpixel((0, 1))) - print (im2.getpixel((0, 2))) + logger.debug("%s", [img.getpixel((0, idx)) + for img in [im, im2] for idx in range(3)]) self.assert_image_equal(im, im2) diff --git a/Tests/test_file_tiff.py b/Tests/test_file_tiff.py index 32aef075e..15a8cef0a 100644 --- a/Tests/test_file_tiff.py +++ b/Tests/test_file_tiff.py @@ -1,7 +1,11 @@ +import logging + from helper import unittest, PillowTestCase, hopper, py3 from PIL import Image, TiffImagePlugin +logger = logging.getLogger(__name__) + class TestFileTiff(PillowTestCase): @@ -109,7 +113,6 @@ class TestFileTiff(PillowTestCase): """ Are we generating the same interpretation of the image as Imagemagick is? """ - # Image.DEBUG = True im = Image.open('Tests/images/12bit.cropped.tif') # to make the target -- @@ -120,14 +123,8 @@ class TestFileTiff(PillowTestCase): im2 = Image.open('Tests/images/12in16bit.tif') - if Image.DEBUG: - print (im.getpixel((0, 0))) - print (im.getpixel((0, 1))) - print (im.getpixel((0, 2))) - - print (im2.getpixel((0, 0))) - print (im2.getpixel((0, 1))) - print (im2.getpixel((0, 2))) + logger.debug("%s", [img.getpixel((0, idx)) + for img in [im, im2] for idx in range(3)]) self.assert_image_equal(im, im2) diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py index 62a83cda6..8991aa9c2 100644 --- a/Tests/test_imagesequence.py +++ b/Tests/test_imagesequence.py @@ -23,14 +23,11 @@ class TestImageSequence(PillowTestCase): self.assertEqual(index, 1) def _test_multipage_tiff(self, dbg=False): - # debug had side effect of calling fp.tell. - Image.DEBUG=dbg im = Image.open('Tests/images/multipage.tiff') for index, frame in enumerate(ImageSequence.Iterator(im)): frame.load() self.assertEqual(index, im.tell()) frame.convert('RGB') - Image.DEBUG=False def test_tiff(self): #self._test_multipage_tiff(True)