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.
This commit is contained in:
Antony Lee 2015-02-06 10:58:07 -08:00
parent d46441b789
commit 60b4f88f17
10 changed files with 61 additions and 82 deletions

View File

@ -28,8 +28,11 @@ from __future__ import print_function
from PIL import VERSION, PILLOW_VERSION, _plugins from PIL import VERSION, PILLOW_VERSION, _plugins
import logging
import warnings import warnings
logger = logging.getLogger(__name__)
class DecompressionBombWarning(RuntimeWarning): class DecompressionBombWarning(RuntimeWarning):
pass pass
@ -138,11 +141,6 @@ def isImageType(t):
""" """
return hasattr(t, "im") return hasattr(t, "im")
#
# Debug level
DEBUG = 0
# #
# Constants (also defined in _imagingmodule.c!) # Constants (also defined in _imagingmodule.c!)
@ -386,13 +384,10 @@ def init():
for plugin in _plugins: for plugin in _plugins:
try: try:
if DEBUG: logger.debug("Importing %s", plugin)
print ("Importing %s" % plugin)
__import__("PIL.%s" % plugin, globals(), locals(), []) __import__("PIL.%s" % plugin, globals(), locals(), [])
except ImportError: except ImportError as e:
if DEBUG: logger.debug("Image: failed to import %s: %s", plugin, e)
print("Image: failed to import", end=' ')
print(plugin, ":", sys.exc_info()[1])
if OPEN or SAVE: if OPEN or SAVE:
_initialized = 2 _initialized = 2
@ -545,8 +540,7 @@ class Image:
try: try:
self.fp.close() self.fp.close()
except Exception as msg: except Exception as msg:
if DEBUG: logger.debug("Error closing: %s" % msg)
print ("Error closing: %s" % msg)
# Instead of simply setting to None, we're setting up a # Instead of simply setting to None, we're setting up a
# deferred error that will better explain that the core image # deferred error that will better explain that the core image

View File

@ -30,10 +30,13 @@
from PIL import Image from PIL import Image
from PIL._util import isPath from PIL._util import isPath
import io import io
import logging
import os import os
import sys import sys
import traceback import traceback
logger = logging.getLogger(__name__)
MAXBLOCK = 65536 MAXBLOCK = 65536
SAFEBLOCK = 1024*1024 SAFEBLOCK = 1024*1024
@ -95,22 +98,11 @@ class ImageFile(Image.Image):
try: try:
self._open() self._open()
except IndexError as v: # end of data except (IndexError, # end of data
if Image.DEBUG > 1: TypeError, # end of data (ord)
traceback.print_exc() KeyError, # unsupported mode
raise SyntaxError(v) EOFError) as v: # got header but not the first frame
except TypeError as v: # end of data (ord) logger.exception("%s")
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)
if not self.mode or self.size[0] <= 0: if not self.mode or self.size[0] <= 0:
raise SyntaxError("not identified by this driver") raise SyntaxError("not identified by this driver")

View File

@ -27,8 +27,11 @@
__version__ = "0.6" __version__ = "0.6"
import logging
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
logger = logging.getLogger(__name__)
i8 = _binary.i8 i8 = _binary.i8
i16 = _binary.i16le i16 = _binary.i16le
o8 = _binary.o8 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 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]: if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
raise SyntaxError("bad PCX image size") raise SyntaxError("bad PCX image size")
if Image.DEBUG: logger.debug("BBox: %s %s %s %s", *bbox)
print ("BBox: %s %s %s %s" % bbox)
# format # format
version = i8(s[1]) version = i8(s[1])
bits = i8(s[3]) bits = i8(s[3])
planes = i8(s[65]) planes = i8(s[65])
stride = i16(s, 66) stride = i16(s, 66)
if Image.DEBUG: logger.debug("PCX version %s, bits %s, planes %s, stride %s",
print ("PCX version %s, bits %s, planes %s, stride %s" % version, bits, planes, stride)
(version, bits, planes, stride))
self.info["dpi"] = i16(s, 12), i16(s, 14) 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] self.size = bbox[2]-bbox[0], bbox[3]-bbox[1]
bbox = (0, 0) + self.size bbox = (0, 0) + self.size
if Image.DEBUG: logger.debug("size: %sx%s", *self.size)
print ("size: %sx%s" % self.size)
self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))] self.tile = [("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))]
@ -142,8 +142,7 @@ def _save(im, fp, filename, check=0):
# Ideally it should be passed in in the state, but the bytes value # Ideally it should be passed in in the state, but the bytes value
# gets overwritten. # gets overwritten.
if Image.DEBUG: logger.debug("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
print ("PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d" % (
im.size[0], bits, stride)) im.size[0], bits, stride))
# under windows, we could determine the current screen size with # under windows, we could determine the current screen size with

View File

@ -35,10 +35,13 @@ from __future__ import print_function
__version__ = "0.9" __version__ = "0.9"
import logging
import re import re
import zlib
from PIL import Image, ImageFile, ImagePalette, _binary from PIL import Image, ImageFile, ImagePalette, _binary
import zlib
logger = logging.getLogger(__name__)
i8 = _binary.i8 i8 = _binary.i8
i16 = _binary.i16be i16 = _binary.i16be
@ -127,8 +130,7 @@ class ChunkStream:
def call(self, cid, pos, length): def call(self, cid, pos, length):
"Call the appropriate chunk handler" "Call the appropriate chunk handler"
if Image.DEBUG: logger.debug("STREAM %s %s %s", cid, pos, length)
print("STREAM", cid, pos, length)
return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length) return getattr(self, "chunk_" + cid.decode('ascii'))(pos, length)
def crc(self, cid, data): def crc(self, cid, data):
@ -291,9 +293,8 @@ class PngStream(ChunkStream):
# Compression method 1 byte (0) # Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression) # Compressed profile n bytes (zlib with deflate compression)
i = s.find(b"\0") i = s.find(b"\0")
if Image.DEBUG: logger.debug("iCCP profile name %s", s[:i])
print("iCCP profile name", s[:i]) logger.debug("Compression method %s", i8(s[i]))
print("Compression method", i8(s[i]))
comp_method = i8(s[i]) comp_method = i8(s[i])
if comp_method != 0: if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" % raise SyntaxError("Unknown compression method %s in iCCP chunk" %
@ -503,8 +504,7 @@ class PngImageFile(ImageFile.ImageFile):
except EOFError: except EOFError:
break break
except AttributeError: except AttributeError:
if Image.DEBUG: logger.debug("%s %s %s (unknown)", cid, pos, length)
print(cid, pos, length, "(unknown)")
s = ImageFile._safe_read(self.fp, length) s = ImageFile._safe_read(self.fp, length)
self.png.crc(cid, s) self.png.crc(cid, s)

View File

@ -22,10 +22,14 @@
from __future__ import print_function from __future__ import print_function
from cffi import FFI import logging
import sys import sys
DEBUG = 0 from cffi import FFI
logger = logging.getLogger(__name__)
defs = """ defs = """
struct Pixel_RGBA { struct Pixel_RGBA {
@ -50,8 +54,7 @@ class PyAccess(object):
self.xsize = vals['xsize'] self.xsize = vals['xsize']
self.ysize = vals['ysize'] self.ysize = vals['ysize']
if DEBUG: logger.debug("%s", vals)
print (vals)
self._post_init() self._post_init()
def _post_init(self): def _post_init(self):
@ -305,11 +308,9 @@ else:
def new(img, readonly=False): def new(img, readonly=False):
access_type = mode_map.get(img.mode, None) access_type = mode_map.get(img.mode, None)
if not access_type: if not access_type:
if DEBUG: logger.debug("PyAccess Not Implemented: %s", img.mode)
print("PyAccess Not Implemented: %s" % img.mode)
return None return None
if DEBUG: logger.debug("New PyAccess: %s", img.mode)
print("New PyAccess: %s" % img.mode)
return access_type(img, readonly) return access_type(img, readonly)
# End of file # End of file

View File

@ -19,8 +19,11 @@
from __future__ import print_function from __future__ import print_function
import getopt
import glob
import logging
import site import site
import getopt, glob, sys import sys
from PIL import Image from PIL import Image
@ -41,6 +44,7 @@ except getopt.error as v:
sys.exit(1) sys.exit(1)
verbose = quiet = verify = 0 verbose = quiet = verify = 0
logging_level = "WARNING"
for o, a in opt: for o, a in opt:
if o == "-f": if o == "-f":
@ -57,7 +61,9 @@ for o, a in opt:
elif o == "-v": elif o == "-v":
verify = 1 verify = 1
elif o == "-D": elif o == "-D":
Image.DEBUG += 1 logging_level = "DEBUG"
logging.basicConfig(level=logging_level)
def globfix(files): def globfix(files):
# expand wildcards where necessary # expand wildcards where necessary

View File

@ -15,9 +15,6 @@ from PIL import Image, ImageTk
import sys import sys
Image.DEBUG = 0
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# an image animation player # an image animation player

View File

@ -1,10 +1,13 @@
from helper import unittest, PillowTestCase, hopper, py3 from helper import unittest, PillowTestCase, hopper, py3
import os
import io import io
import logging
import os
from PIL import Image, TiffImagePlugin from PIL import Image, TiffImagePlugin
logger = logging.getLogger(__name__)
class LibTiffTestCase(PillowTestCase): class LibTiffTestCase(PillowTestCase):
@ -230,7 +233,6 @@ class TestFileLibTiff(LibTiffTestCase):
""" Are we generating the same interpretation """ Are we generating the same interpretation
of the image as Imagemagick is? """ of the image as Imagemagick is? """
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
# Image.DEBUG = True
im = Image.open('Tests/images/12bit.cropped.tif') im = Image.open('Tests/images/12bit.cropped.tif')
im.load() im.load()
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
@ -242,14 +244,8 @@ class TestFileLibTiff(LibTiffTestCase):
im2 = Image.open('Tests/images/12in16bit.tif') im2 = Image.open('Tests/images/12in16bit.tif')
if Image.DEBUG: logger.debug("%s", [img.getpixel((0, idx))
print (im.getpixel((0, 0))) for img in [im, im2] for idx in range(3)])
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)))
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)

View File

@ -1,7 +1,11 @@
import logging
from helper import unittest, PillowTestCase, hopper, py3 from helper import unittest, PillowTestCase, hopper, py3
from PIL import Image, TiffImagePlugin from PIL import Image, TiffImagePlugin
logger = logging.getLogger(__name__)
class TestFileTiff(PillowTestCase): class TestFileTiff(PillowTestCase):
@ -109,7 +113,6 @@ class TestFileTiff(PillowTestCase):
""" Are we generating the same interpretation """ Are we generating the same interpretation
of the image as Imagemagick is? """ of the image as Imagemagick is? """
# Image.DEBUG = True
im = Image.open('Tests/images/12bit.cropped.tif') im = Image.open('Tests/images/12bit.cropped.tif')
# to make the target -- # to make the target --
@ -120,14 +123,8 @@ class TestFileTiff(PillowTestCase):
im2 = Image.open('Tests/images/12in16bit.tif') im2 = Image.open('Tests/images/12in16bit.tif')
if Image.DEBUG: logger.debug("%s", [img.getpixel((0, idx))
print (im.getpixel((0, 0))) for img in [im, im2] for idx in range(3)])
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)))
self.assert_image_equal(im, im2) self.assert_image_equal(im, im2)

View File

@ -23,14 +23,11 @@ class TestImageSequence(PillowTestCase):
self.assertEqual(index, 1) self.assertEqual(index, 1)
def _test_multipage_tiff(self, dbg=False): 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') im = Image.open('Tests/images/multipage.tiff')
for index, frame in enumerate(ImageSequence.Iterator(im)): for index, frame in enumerate(ImageSequence.Iterator(im)):
frame.load() frame.load()
self.assertEqual(index, im.tell()) self.assertEqual(index, im.tell())
frame.convert('RGB') frame.convert('RGB')
Image.DEBUG=False
def test_tiff(self): def test_tiff(self):
#self._test_multipage_tiff(True) #self._test_multipage_tiff(True)