From ee244406ee12cdcfe451c28e665b75fe08cf9057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Schoentgen?= Date: Tue, 25 Sep 2018 23:04:26 +0200 Subject: [PATCH 1/4] Fix several ResourceWarning: unclosed file in subset --- Lib/fontTools/subset/__init__.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Lib/fontTools/subset/__init__.py b/Lib/fontTools/subset/__init__.py index 989c98be3..4450e18dc 100644 --- a/Lib/fontTools/subset/__init__.py +++ b/Lib/fontTools/subset/__init__.py @@ -3253,7 +3253,8 @@ def main(args=None): text += g[7:] continue if g.startswith('--text-file='): - text += open(g[12:], encoding='utf-8').read().replace('\n', '') + with open(g[12:], encoding='utf-8') as f: + text += f.read().replace('\n', '') continue if g.startswith('--unicodes='): if g[11:] == '*': @@ -3262,15 +3263,17 @@ def main(args=None): unicodes.extend(parse_unicodes(g[11:])) continue if g.startswith('--unicodes-file='): - for line in open(g[16:]).readlines(): - unicodes.extend(parse_unicodes(line.split('#')[0])) + with open(g[16:]) as f: + for line in f.readlines(): + unicodes.extend(parse_unicodes(line.split('#')[0])) continue if g.startswith('--gids='): gids.extend(parse_gids(g[7:])) continue if g.startswith('--gids-file='): - for line in open(g[12:]).readlines(): - gids.extend(parse_gids(line.split('#')[0])) + with open(g[12:]) as f: + for line in f.readlines(): + gids.extend(parse_gids(line.split('#')[0])) continue if g.startswith('--glyphs='): if g[9:] == '*': @@ -3279,8 +3282,9 @@ def main(args=None): glyphs.extend(parse_glyphs(g[9:])) continue if g.startswith('--glyphs-file='): - for line in open(g[14:]).readlines(): - glyphs.extend(parse_glyphs(line.split('#')[0])) + with open(g[14:]) as f: + for line in f.readlines(): + glyphs.extend(parse_glyphs(line.split('#')[0])) continue glyphs.append(g) From 698aa676e8703ea585d279242430db7064c1b535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Schoentgen?= Date: Tue, 25 Sep 2018 23:17:34 +0200 Subject: [PATCH 2/4] Fix ResourceWarning: unclosed file in mtiLib --- Lib/fontTools/mtiLib/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/fontTools/mtiLib/__init__.py b/Lib/fontTools/mtiLib/__init__.py index d4f4880ae..beec5cb5a 100644 --- a/Lib/fontTools/mtiLib/__init__.py +++ b/Lib/fontTools/mtiLib/__init__.py @@ -1174,7 +1174,8 @@ def main(args=None, font=None): del args[0] for f in args: log.debug("Processing %s", f) - table = build(open(f, 'rt', encoding="utf-8"), font, tableTag=tableTag) + with open(f, 'rt', encoding="utf-8") as f: + table = build(f, font, tableTag=tableTag) blob = table.compile(font) # Make sure it compiles decompiled = table.__class__() decompiled.decompile(blob, font) # Make sure it decompiles! From bfde7268c36e1c19d56547b2390c1c7e3580ce7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Schoentgen?= Date: Tue, 25 Sep 2018 23:18:21 +0200 Subject: [PATCH 3/4] Fix ResourceWarning: unclosed file in MetaTools --- MetaTools/buildTableList.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/MetaTools/buildTableList.py b/MetaTools/buildTableList.py index de8a039db..eb9fb8580 100755 --- a/MetaTools/buildTableList.py +++ b/MetaTools/buildTableList.py @@ -30,9 +30,9 @@ modules.sort() tables.sort() -file = open(os.path.join(tablesDir, "__init__.py"), "w") +with open(os.path.join(tablesDir, "__init__.py"), "w") as file: -file.write(''' + file.write(''' from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * @@ -45,21 +45,20 @@ def _moduleFinderHint(): """ ''') -for module in modules: - file.write("\tfrom . import %s\n" % module) + for module in modules: + file.write("\tfrom . import %s\n" % module) -file.write(''' + file.write(''' if __name__ == "__main__": import doctest, sys sys.exit(doctest.testmod().failed) ''') -file.close() - begin = ".. begin table list\n.. code::\n" end = ".. end table list" -doc = open(docFile).read() +with open(docFile) as f: + doc = f.read() beginPos = doc.find(begin) assert beginPos > 0 beginPos = beginPos + len(begin) + 1 @@ -70,4 +69,5 @@ blockquote = "\n".join(" "*4 + line for line in lines) + "\n" doc = doc[:beginPos] + blockquote + doc[endPos:] -open(docFile, "w").write(doc) +with open(docFile, "w") as f: + f.write(doc) From 52e855e4a412bcbeec9a210938a6912a9097383f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Schoentgen?= Date: Tue, 25 Sep 2018 23:27:51 +0200 Subject: [PATCH 4/4] Use the 'with' context manager when dealing with files --- Lib/fontTools/t1Lib/__init__.py | 54 ++++++++++-------------- Lib/fontTools/ttx.py | 6 +-- Lib/fontTools/unicode.py | 7 ++- MetaTools/roundTrip.py | 33 +++++++-------- Tests/designspaceLib/designspace_test.py | 30 ++++++------- 5 files changed, 58 insertions(+), 72 deletions(-) diff --git a/Lib/fontTools/t1Lib/__init__.py b/Lib/fontTools/t1Lib/__init__.py index 5da9cea46..00485e463 100644 --- a/Lib/fontTools/t1Lib/__init__.py +++ b/Lib/fontTools/t1Lib/__init__.py @@ -164,9 +164,8 @@ def readLWFN(path, onlyHeader=False): elif code in [3, 5]: break elif code == 4: - f = open(path, "rb") - data.append(f.read()) - f.close() + with open(path, "rb") as f: + data.append(f.read()) elif code == 0: pass # comment, ignore else: @@ -179,35 +178,32 @@ def readLWFN(path, onlyHeader=False): def readPFB(path, onlyHeader=False): """reads a PFB font file, returns raw data""" - f = open(path, "rb") data = [] - while True: - if f.read(1) != bytechr(128): - raise T1Error('corrupt PFB file') - code = byteord(f.read(1)) - if code in [1, 2]: - chunklen = stringToLong(f.read(4)) - chunk = f.read(chunklen) - assert len(chunk) == chunklen - data.append(chunk) - elif code == 3: - break - else: - raise T1Error('bad chunk code: ' + repr(code)) - if onlyHeader: - break - f.close() + with open(path, "rb") as f: + while True: + if f.read(1) != bytechr(128): + raise T1Error('corrupt PFB file') + code = byteord(f.read(1)) + if code in [1, 2]: + chunklen = stringToLong(f.read(4)) + chunk = f.read(chunklen) + assert len(chunk) == chunklen + data.append(chunk) + elif code == 3: + break + else: + raise T1Error('bad chunk code: ' + repr(code)) + if onlyHeader: + break data = bytesjoin(data) assertType1(data) return data def readOther(path): """reads any (font) file, returns raw data""" - f = open(path, "rb") - data = f.read() - f.close() + with open(path, "rb") as f: + data = f.read() assertType1(data) - chunks = findEncryptedChunks(data) data = [] for isEncrypted, chunk in chunks: @@ -244,8 +240,7 @@ def writeLWFN(path, data): def writePFB(path, data): chunks = findEncryptedChunks(data) - f = open(path, "wb") - try: + with open(path, "wb") as f: for isEncrypted, chunk in chunks: if isEncrypted: code = 2 @@ -255,13 +250,10 @@ def writePFB(path, data): f.write(longToString(len(chunk))) f.write(chunk) f.write(bytechr(128) + bytechr(3)) - finally: - f.close() def writeOther(path, data, dohex=False): chunks = findEncryptedChunks(data) - f = open(path, "wb") - try: + with open(path, "wb") as f: hexlinelen = HEXLINELENGTH // 2 for isEncrypted, chunk in chunks: if isEncrypted: @@ -275,8 +267,6 @@ def writeOther(path, data, dohex=False): chunk = chunk[hexlinelen:] else: f.write(chunk) - finally: - f.close() # decryption tools diff --git a/Lib/fontTools/ttx.py b/Lib/fontTools/ttx.py index 0e3eaf39c..a785325e4 100644 --- a/Lib/fontTools/ttx.py +++ b/Lib/fontTools/ttx.py @@ -293,11 +293,11 @@ def ttCompile(input, output, options): def guessFileType(fileName): base, ext = os.path.splitext(fileName) try: - f = open(fileName, "rb") + with open(fileName, "rb") as f: + header = f.read(256) except IOError: return None - header = f.read(256) - f.close() + if header.startswith(b'\xef\xbb\xbf', '\n\t') - f = open(path, 'w', encoding='utf-8') - f.write(d) - f.close() + with open(path, 'w', encoding='utf-8') as f: + f.write(d) def test_documentLib(tmpdir): # roundtrip test of the document lib with some nested data