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
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

View File

@ -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")

View File

@ -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,8 +142,7 @@ 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" % (
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

View File

@ -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)

View File

@ -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

View File

@ -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

View File

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

View File

@ -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)

View File

@ -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)

View File

@ -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)