From a06dd59df757d9c9cef0b132c4b123d85dcbe3c0 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 28 Dec 2016 09:54:10 +1100 Subject: [PATCH] Added context managers --- PIL/GifImagePlugin.py | 22 ++++++++++------------ PIL/IcnsImagePlugin.py | 4 ++-- PIL/SpiderImagePlugin.py | 5 ++--- Tests/helper.py | 2 +- Tests/test_file_gif.py | 26 ++++++++++++-------------- Tests/test_file_ppm.py | 9 ++++----- Tests/test_image.py | 10 +++++----- Tests/test_psdraw.py | 10 ++++------ setup.py | 5 ++--- 9 files changed, 42 insertions(+), 51 deletions(-) diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py index 41d6dcc1d..a50af6c02 100644 --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -521,22 +521,20 @@ def _save_netpbm(im, fp, filename): import tempfile file = im._dump() - if im.mode != "RGB": - with open(filename, 'wb') as f: - stderr = tempfile.TemporaryFile() - check_call(["ppmtogif", file], stdout=f, stderr=stderr) - else: - with open(filename, 'wb') as f: - + with open(filename, 'wb') as f: + if im.mode != "RGB": + with tempfile.TemporaryFile() as stderr: + check_call(["ppmtogif", file], stdout=f, stderr=stderr) + else: # Pipe ppmquant output into ppmtogif # "ppmquant 256 %s | ppmtogif > %s" % (file, filename) quant_cmd = ["ppmquant", "256", file] togif_cmd = ["ppmtogif"] - stderr = tempfile.TemporaryFile() - quant_proc = Popen(quant_cmd, stdout=PIPE, stderr=stderr) - stderr = tempfile.TemporaryFile() - togif_proc = Popen(togif_cmd, stdin=quant_proc.stdout, stdout=f, - stderr=stderr) + with tempfile.TemporaryFile() as stderr: + quant_proc = Popen(quant_cmd, stdout=PIPE, stderr=stderr) + with tempfile.TemporaryFile() as stderr: + togif_proc = Popen(togif_cmd, stdin=quant_proc.stdout, + stdout=f, stderr=stderr) # Allow ppmquant to receive SIGPIPE if ppmtogif exits quant_proc.stdout.close() diff --git a/PIL/IcnsImagePlugin.py b/PIL/IcnsImagePlugin.py index d93e0de04..089fc2a44 100644 --- a/PIL/IcnsImagePlugin.py +++ b/PIL/IcnsImagePlugin.py @@ -330,8 +330,8 @@ def _save(im, fp, filename): from subprocess import Popen, PIPE, CalledProcessError convert_cmd = ["iconutil", "-c", "icns", "-o", filename, iconset] - stderr = tempfile.TemporaryFile() - convert_proc = Popen(convert_cmd, stdout=PIPE, stderr=stderr) + with tempfile.TemporaryFile() as stderr: + convert_proc = Popen(convert_cmd, stdout=PIPE, stderr=stderr) convert_proc.stdout.close() diff --git a/PIL/SpiderImagePlugin.py b/PIL/SpiderImagePlugin.py index 5c4d1bb3b..aa332bf02 100644 --- a/PIL/SpiderImagePlugin.py +++ b/PIL/SpiderImagePlugin.py @@ -83,9 +83,8 @@ def isSpiderHeader(t): def isSpiderImage(filename): - fp = open(filename, 'rb') - f = fp.read(92) # read 23 * 4 bytes - fp.close() + with open(filename, 'rb') as fp: + f = fp.read(92) # read 23 * 4 bytes t = struct.unpack('>23f', f) # try big-endian first hdrlen = isSpiderHeader(t) if hdrlen == 0: diff --git a/Tests/helper.py b/Tests/helper.py index c5ec253ca..f4b6b52cf 100644 --- a/Tests/helper.py +++ b/Tests/helper.py @@ -151,7 +151,7 @@ class PillowTestCase(unittest.TestCase): def tempfile(self, template): assert template[:5] in ("temp.", "temp_") - (fd, path) = tempfile.mkstemp(template[4:], template[:4]) + fd, path = tempfile.mkstemp(template[4:], template[:4]) os.close(fd) self.addCleanup(self.delete_tempfile, path) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 94a8ea92c..d987f6851 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -56,7 +56,7 @@ class TestFileGif(PillowTestCase): # 256 color Palette image, posterize to > 128 and < 128 levels # Size bigger and smaller than 512x512 # Check the palette for number of colors allocated. - # Check for correctness after conversion back to RGB + # Check for correctness after conversion back to RGB def check(colors, size, expected_palette_length): # make an image with empty colors in the start of the palette range im = Image.frombytes('P', (colors,colors), @@ -70,7 +70,7 @@ class TestFileGif(PillowTestCase): # check palette length palette_length = max(i+1 for i,v in enumerate(reloaded.histogram()) if v) self.assertEqual(expected_palette_length, palette_length) - + self.assert_image_equal(im.convert('RGB'), reloaded.convert('RGB')) @@ -271,12 +271,11 @@ class TestFileGif(PillowTestCase): duration = 1000 out = self.tempfile('temp.gif') - fp = open(out, "wb") - im = Image.new('L', (100, 100), '#000') - for s in GifImagePlugin.getheader(im)[0] + GifImagePlugin.getdata(im, duration=duration): - fp.write(s) - fp.write(b";") - fp.close() + with open(out, "wb") as fp: + im = Image.new('L', (100, 100), '#000') + for s in GifImagePlugin.getheader(im)[0] + GifImagePlugin.getdata(im, duration=duration): + fp.write(s) + fp.write(b";") reread = Image.open(out) self.assertEqual(reread.info['duration'], duration) @@ -329,12 +328,11 @@ class TestFileGif(PillowTestCase): number_of_loops = 2 out = self.tempfile('temp.gif') - fp = open(out, "wb") - im = Image.new('L', (100, 100), '#000') - for s in GifImagePlugin.getheader(im)[0] + GifImagePlugin.getdata(im, loop=number_of_loops): - fp.write(s) - fp.write(b";") - fp.close() + with open(out, "wb") as fp: + im = Image.new('L', (100, 100), '#000') + for s in GifImagePlugin.getheader(im)[0] + GifImagePlugin.getdata(im, loop=number_of_loops): + fp.write(s) + fp.write(b";") reread = Image.open(out) self.assertEqual(reread.info['loop'], number_of_loops) diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py index e7428f88d..a798466b7 100644 --- a/Tests/test_file_ppm.py +++ b/Tests/test_file_ppm.py @@ -36,9 +36,8 @@ class TestFilePpm(PillowTestCase): def test_truncated_file(self): path = self.tempfile('temp.pgm') - f = open(path, 'w') - f.write('P6') - f.close() + with open(path, 'w') as f: + f.write('P6') self.assertRaises(ValueError, lambda: Image.open(path)) @@ -47,8 +46,8 @@ class TestFilePpm(PillowTestCase): # Storage.c accepted negative values for xsize, ysize. the # internal open_ppm function didn't check for sanity but it # has been removed. The default opener doesn't accept negative - # sizes. - + # sizes. + with self.assertRaises(IOError): Image.open('Tests/images/negative_size.ppm') diff --git a/Tests/test_image.py b/Tests/test_image.py index ef9aa16af..8515a030a 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -80,11 +80,11 @@ class TestImage(PillowTestCase): # Will error out on save on 3.0.0 import tempfile im = hopper() - fp = tempfile.TemporaryFile() - im.save(fp, 'JPEG') - fp.seek(0) - reloaded = Image.open(fp) - self.assert_image_similar(im, reloaded, 20) + with tempfile.TemporaryFile() as fp: + im.save(fp, 'JPEG') + fp.seek(0) + reloaded = Image.open(fp) + self.assert_image_similar(im, reloaded, 20) def test_internals(self): diff --git a/Tests/test_psdraw.py b/Tests/test_psdraw.py index 31a2de33d..50e8763e2 100644 --- a/Tests/test_psdraw.py +++ b/Tests/test_psdraw.py @@ -35,12 +35,10 @@ class TestPsDraw(PillowTestCase): # Arrange tempfile = self.tempfile('temp.ps') - fp = open(tempfile, "wb") - - # Act - ps = PSDraw.PSDraw(fp) - self._create_document(ps) - fp.close() + with open(tempfile, "wb") as fp: + # Act + ps = PSDraw.PSDraw(fp) + self._create_document(ps) # Assert # Check non-zero file was created diff --git a/setup.py b/setup.py index c35d4357c..e93514366 100755 --- a/setup.py +++ b/setup.py @@ -728,9 +728,8 @@ class pil_build_ext(build_ext): return try: if ret >> 8 == 0: - fp = open(tmpfile, 'r') - multiarch_path_component = fp.readline().strip() - fp.close() + with open(tmpfile, 'r') as fp: + multiarch_path_component = fp.readline().strip() _add_directory(self.compiler.library_dirs, '/usr/lib/' + multiarch_path_component) _add_directory(self.compiler.include_dirs,