From 1c24b88574dd34539aa8ce96c31bbd1a8b0ac8e3 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Andr=C3=A9=20Wobst?= Date: Tue, 16 Jul 2013 21:48:33 +0000 Subject: [PATCH] use with statement for file operations (where appropriate) git-svn-id: http://svn.code.sf.net/p/pyx/code/trunk/pyx@3456 a4f5e268-e194-4f32-bce1-d30804cbbcc5 --- pyx/bitmap.py | 5 +- pyx/canvas.py | 27 ++-- pyx/config.py | 63 ++++---- pyx/document.py | 48 +++--- pyx/dvi/dvifile.py | 7 +- pyx/dvi/mapfile.py | 61 ++++---- pyx/dvi/texfont.py | 6 +- pyx/dvi/tfmfile.py | 422 ++++++++++++++++++++++++++--------------------------- pyx/dvi/vffile.py | 2 - pyx/epsfile.py | 13 +- pyx/font/t1file.py | 15 +- pyx/graph/data.py | 5 +- pyx/pattern.py | 2 - pyx/pdfwriter.py | 2 - pyx/pswriter.py | 3 - pyx/reader.py | 12 +- pyx/text.py | 18 +-- pyx/writer.py | 7 +- 18 files changed, 349 insertions(+), 369 deletions(-) rewrite pyx/dvi/tfmfile.py (77%) diff --git a/pyx/bitmap.py b/pyx/bitmap.py index 89e4951d..dd62c0c5 100644 --- a/pyx/bitmap.py +++ b/pyx/bitmap.py @@ -130,9 +130,8 @@ class jpegimage(image): try: data = file.read() except: - f = open(file, "rb") - data = f.read() - f.close() + with open(file, "rb") as f: + data = f.read() pos = 0 nestinglevel = 0 try: diff --git a/pyx/canvas.py b/pyx/canvas.py index ccca7a55..7d31c2a6 100644 --- a/pyx/canvas.py +++ b/pyx/canvas.py @@ -415,17 +415,15 @@ class canvas(baseclasses.canvasitem): if input == "eps": gscmd += " -" - stdin = pycompat.popen(gscmd, "wb") - self.writeEPSfile(stdin, **kwargs) - stdin.close() + with pycompat.popen(gscmd, "wb") as stdin: + self.writeEPSfile(stdin, **kwargs) elif input == "pdf": # PDF files need to be accesible by random access and thus we need to create # a temporary file - fd, fname = tempfile.mkstemp() - f = os.fdopen(fd, "wb") - gscmd += " %s" % fname - self.writePDFfile(f, **kwargs) - f.close() + with tempfile.NamedTemporaryFile("wb", delete=False) as f: + gscmd += " %s" % f.name + self.writePDFfile(f, **kwargs) + fname = f.name os.system(gscmd) os.unlink(fname) else: @@ -436,7 +434,7 @@ class canvas(baseclasses.canvasitem): """ returns a pipe with the Ghostscript output of the EPS or PDF of the canvas - If seekable is True, a StringIO instance will be returned instead of a + If seekable is True, a BytesIO instance will be returned instead of a pipe to allow random access. """ @@ -452,11 +450,10 @@ class canvas(baseclasses.canvasitem): elif input == "pdf": # PDF files need to be accesible by random access and thus we need to create # a temporary file - fd, fname = tempfile.mkstemp() - f = os.fdopen(fd, "wb") - gscmd += " %s" % fname - self.writePDFfile(f, **kwargs) - f.close() + with tempfile.NamedTemporaryFile("wb", delete=False) as f: + gscmd += " %s" % f.name + self.writePDFfile(f, **kwargs) + fname = f.name stdout = pycompat.popen(gscmd, "rb") os.unlink(fname) else: @@ -464,7 +461,7 @@ class canvas(baseclasses.canvasitem): if seekable: # the read method of a pipe object may not return the full content - f = io.StringIO() + f = io.BytesIO() while True: data = stdout.read() if not data: diff --git a/pyx/config.py b/pyx/config.py index 07c7b3e0..27a80880 100644 --- a/pyx/config.py +++ b/pyx/config.py @@ -130,17 +130,16 @@ class ls_R: base_dir = os.path.dirname(lsr) dir = None first = True - lsrfile = builtinopen(lsr, "r", encoding="ascii", errors="surrogateescape") - for line in lsrfile: - line = line.rstrip() - if first and line.startswith("%"): - continue - first = False - if line.endswith(":"): - dir = os.path.join(base_dir, line[:-1]) - elif line: - self.full_filenames[line] = os.path.join(dir, line) - lsrfile.close() + with builtinopen(lsr, "r", encoding="ascii", errors="surrogateescape") as lsrfile: + for line in lsrfile: + line = line.rstrip() + if first and line.startswith("%"): + continue + first = False + if line.endswith(":"): + dir = os.path.join(base_dir, line[:-1]) + elif line: + self.full_filenames[line] = os.path.join(dir, line) for extension in extensions: if filename+extension in self.full_filenames: def _opener(): @@ -195,9 +194,8 @@ class kpsewhich: def openers(self, filename, names, extensions): for name in names: try: - output = pycompat.popen('kpsewhich --format="%s" "%s"' % (name, filename)) - full_filenames = output.read() - output.close() + with pycompat.popen('kpsewhich --format="%s" "%s"' % (name, filename)) as output: + full_filenames = output.read() except OSError: return [] if full_filenames: @@ -335,21 +333,28 @@ def open(filename, formats, ascii=False): extensions.add(extension) names = tuple([format.name for format in formats]) if (filename, names) in opener_cache: - return opener_cache[(filename, names)]() - for method in methods: - openers = method.openers(filename, names, extensions) - for opener in openers: - try: - file = opener() - except IOError: - file = None - if file: - opener_cache[(filename, names)] = opener - if ascii: - return io.TextIOWrapper(file, encoding="ascii", errors="surrogateescape") - else: - return file - raise IOError("Could not locate the file '%s'." % filename) + file = opener_cache[(filename, names)]() + else: + for method in methods: + openers = method.openers(filename, names, extensions) + for opener in openers: + try: + file = opener() + except EnvironmentError: + file = None + if file: + opener_cache[(filename, names)] = opener + break + # break two loops here + else: + continue + break + else: + raise IOError("Could not locate the file '%s'." % filename) + if ascii: + return io.TextIOWrapper(file, encoding="ascii", errors="surrogateescape") + else: + return file class format: diff --git a/pyx/document.py b/pyx/document.py index 78c989bb..8b3bacf9 100644 --- a/pyx/document.py +++ b/pyx/document.py @@ -132,22 +132,33 @@ class page: self._process("processPDF", *args) +class _noclose: + + def __init__(self, f): + self.f = f + + def __enter__(self): + return self.f + + def __exit__(self, type, value, tb): + pass + + def _outputstream(file, suffix): - """returns a tuple: the open file handler and a boolean indicating - whether the file should be closed at the end or not""" if file is None: if not sys.argv[0].endswith(".py"): raise RuntimeError("could not auto-guess filename") - return open("%s.%s" % (sys.argv[0][:-3], suffix), "wb"), True + return open("%s.%s" % (sys.argv[0][:-3], suffix), "wb") if file == "-": - return sys.stdout.buffer, False + return _noclose(sys.stdout.buffer) try: file.write(b"") - return file, True except: if not file.endswith(".%s" % suffix): - return open("%s.%s" % (file, suffix), "wb"), True - return open(file, "wb"), True + return open("%s.%s" % (file, suffix), "wb") + return open(file, "wb") + else: + return _noclose(file) class document: @@ -164,31 +175,24 @@ class document: self.pages.append(page) def writeEPSfile(self, file=None, **kwargs): - f, close = _outputstream(file, "eps") - pswriter.EPSwriter(self, f, **kwargs) - if close: - f.close() + with _outputstream(file, "eps") as f: + pswriter.EPSwriter(self, f, **kwargs) def writePSfile(self, file=None, **kwargs): - f, close = _outputstream(file, "ps") - pswriter.PSwriter(self, f, **kwargs) - if close: - f.close() + with _outputstream(file, "ps") as f: + pswriter.PSwriter(self, f, **kwargs) def writePDFfile(self, file=None, **kwargs): - f, close = _outputstream(file, "pdf") - pdfwriter.PDFwriter(self, f, **kwargs) - if close: - f.close() + with _outputstream(file, "pdf") as f: + pdfwriter.PDFwriter(self, f, **kwargs) def writetofile(self, filename, **kwargs): for suffix, method in [("eps", pswriter.writeEPSfile), ("ps", pswriter.writePSfile), ("pdf", pdfwriter.writePDFfile)]: if filename.endswith(".{}".format(suffix)): - f = open(filename, "wb") - method(self, f, **kwargs) - f.close() + with open(filename, "wb") as f: + method(self, f, **kwargs) return raise ValueError("unknown file extension") diff --git a/pyx/dvi/dvifile.py b/pyx/dvi/dvifile.py index d0318e42..8279ae32 100644 --- a/pyx/dvi/dvifile.py +++ b/pyx/dvi/dvifile.py @@ -200,11 +200,10 @@ class DVIfile: # check whether it's a virtual font by trying to open it. if this fails, it is an ordinary TeX font try: - fontfile = config.open(fontname, [config.format.vf]) - except IOError: + with config.open(fontname, [config.format.vf]) as fontfile: + afont = texfont.virtualfont(fontname, fontfile, c, q/self.tfmconv, d/self.tfmconv, self.tfmconv, self.pyxconv, self.debug>1) + except EnvironmentError: afont = texfont.TeXfont(fontname, c, q/self.tfmconv, d/self.tfmconv, self.tfmconv, self.pyxconv, self.debug>1) - else: - afont = texfont.virtualfont(fontname, fontfile, c, q/self.tfmconv, d/self.tfmconv, self.tfmconv, self.pyxconv, self.debug>1) self.fonts[num] = afont diff --git a/pyx/dvi/mapfile.py b/pyx/dvi/mapfile.py index 982f998b..1d6c2111 100644 --- a/pyx/dvi/mapfile.py +++ b/pyx/dvi/mapfile.py @@ -121,39 +121,33 @@ class MAPline: def getfont(self): if self._font is None: if self.fontfilename is not None: - fontfile = config.open(self.fontfilename, [config.format.type1]) - t1font = t1file.from_PF_bytes(fontfile.read()) - fontfile.close() + with config.open(self.fontfilename, [config.format.type1]) as fontfile: + t1font = t1file.from_PF_bytes(fontfile.read()) assert self.basepsname == t1font.name, "corrupt MAP file" try: - metricfile = config.open(os.path.splitext(self.fontfilename)[0], [config.format.afm], ascii=True) - except IOError: + with config.open(os.path.splitext(self.fontfilename)[0], [config.format.afm], ascii=True) as metricfile: + self._font = font.T1font(t1font, afmfile.AFMfile(metricfile)) + except EnvironmentError: try: # fallback by using the pfm instead of the afm font metric # (in all major TeX distributions there is no pfm file format defined by kpsewhich, but # we can use the type1 format and search for the file including the expected suffix) - metricfile = config.open("%s.pfm" % os.path.splitext(self.fontfilename)[0], [config.format.type1]) - except IOError: + with config.open("%s.pfm" % os.path.splitext(self.fontfilename)[0], [config.format.type1]) as metricfile: + self._font = font.T1font(t1font, pfmfile.PFMfile(metricfile, t1font)) + except EnvironmentError: + # we need to continue without any metric file self._font = font.T1font(t1font) - else: - self._font = font.T1font(t1font, pfmfile.PFMfile(metricfile, t1font)) - metricfile.close() - else: - self._font = font.T1font(t1font, afmfile.AFMfile(metricfile)) - metricfile.close() else: # builtin font - metricfile = config.open(self.basepsname, [config.format.afm], ascii=True) - self._font = font.T1builtinfont(self.basepsname, afmfile.AFMfile(metricfile)) - metricfile.close() + with config.open(self.basepsname, [config.format.afm], ascii=True) as metricfile: + self._font = font.T1builtinfont(self.basepsname, afmfile.AFMfile(metricfile)) return self._font def getencoding(self): if self._encoding is _marker: if self.encodingfilename is not None: - encodingfile = config.open(self.encodingfilename, [config.format.tex_ps_header]) - ef = encfile.ENCfile(encodingfile.read().decode("ascii", errors="surrogateescape")) - encodingfile.close() + with config.open(self.encodingfilename, [config.format.tex_ps_header]) as encodingfile: + ef = encfile.ENCfile(encodingfile.read().decode("ascii", errors="surrogateescape")) assert ef.name == "/%s" % self.reencodefont self._encoding = ef.vector @@ -171,19 +165,18 @@ def readfontmap(filenames): """ read font map from filename (without path) """ fontmap = {} for filename in filenames: - mapfile = config.open(filename, [config.format.fontmap, config.format.dvips_config], ascii=True) - lineno = 0 - for line in mapfile.readlines(): - lineno += 1 - line = line.rstrip() - if not (line=="" or line[0] in (" ", "%", "*", ";" , "#")): - try: - fm = MAPline(line) - except (ParseError, UnsupportedPSFragment) as e: - warnings.warn("Ignoring line %i in mapping file '%s': %s" % (lineno, filename, e)) - except UnsupportedFontFormat as e: - pass - else: - fontmap[fm.texname] = fm - mapfile.close() + with config.open(filename, [config.format.fontmap, config.format.dvips_config], ascii=True) as mapfile: + lineno = 0 + for line in mapfile.readlines(): + lineno += 1 + line = line.rstrip() + if not (line=="" or line[0] in (" ", "%", "*", ";" , "#")): + try: + fm = MAPline(line) + except (ParseError, UnsupportedPSFragment) as e: + warnings.warn("Ignoring line %i in mapping file '%s': %s" % (lineno, filename, e)) + except UnsupportedFontFormat as e: + pass + else: + fontmap[fm.texname] = fm return fontmap diff --git a/pyx/dvi/texfont.py b/pyx/dvi/texfont.py index 0e67fc70..a2a73e50 100644 --- a/pyx/dvi/texfont.py +++ b/pyx/dvi/texfont.py @@ -34,9 +34,8 @@ class TeXfont: self.d = d # design size of font (fix_word) in TeX points self.tfmconv = tfmconv # conversion factor from tfm units to dvi units self.pyxconv = pyxconv # conversion factor from dvi units to PostScript points - file = config.open(self.name, [config.format.tfm]) - self.TFMfile = tfmfile.TFMfile(file, debug) - file.close() + with config.open(self.name, [config.format.tfm]) as file: + self.TFMfile = tfmfile.TFMfile(file, debug) # We only check for equality of font checksums if none of them # is zero. The case c == 0 happend in some VF files and @@ -141,7 +140,6 @@ class virtualfont(TeXfont): def __init__(self, name, file, c, q, d, tfmconv, pyxconv, debug=0): TeXfont.__init__(self, name, c, q, d, tfmconv, pyxconv, debug) self.vffile = vffile.vffile(file, 1.0*q/d, tfmconv, pyxconv, debug > 1) - file.close() def getfonts(self): """ return fonts used in virtual font itself """ diff --git a/pyx/dvi/tfmfile.py b/pyx/dvi/tfmfile.py dissimilarity index 77% index 7965c6f3..67b5ae8f 100644 --- a/pyx/dvi/tfmfile.py +++ b/pyx/dvi/tfmfile.py @@ -1,212 +1,210 @@ -# -*- encoding: utf-8 -*- -# -# -# Copyright (C) 2007-2011 Jörg Lehmann -# Copyright (C) 2007-2011 André Wobst -# -# This file is part of PyX (http://pyx.sourceforge.net/). -# -# PyX is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# PyX is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with PyX; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - - -from pyx import reader - -class char_info_word: - - def __init__(self, word): - self.width_index = int((word & 0xFF000000) >> 24) #make sign-safe - self.height_index = (word & 0x00F00000) >> 20 - self.depth_index = (word & 0x000F0000) >> 16 - self.italic_index = (word & 0x0000FC00) >> 10 - self.tag = (word & 0x00000300) >> 8 - self.remainder = (word & 0x000000FF) - - -class TFMfile: - - def __init__(self, file, debug=0): - self.file = reader.bytesreader(file.read()) - - # - # read pre header - # - - self.lf = self.file.readint16() - self.lh = self.file.readint16() - self.bc = self.file.readint16() - self.ec = self.file.readint16() - self.nw = self.file.readint16() - self.nh = self.file.readint16() - self.nd = self.file.readint16() - self.ni = self.file.readint16() - self.nl = self.file.readint16() - self.nk = self.file.readint16() - self.ne = self.file.readint16() - self.np = self.file.readint16() - - if not (self.bc-1 <= self.ec <= 255 and - self.ne <= 256 and - self.lf == 6+self.lh+(self.ec-self.bc+1)+self.nw+self.nh+self.nd - +self.ni+self.nl+self.nk+self.ne+self.np): - raise RuntimeError("error in TFM pre-header") - - if debug: - print("lh=%d" % self.lh) - - # - # read header - # - - self.checksum = self.file.readint32() - self.designsize = self.file.readint32() - assert self.designsize > 0, "invald design size" - if self.lh > 2: - assert self.lh > 11, "inconsistency in TFM file: incomplete field" - self.charcoding = self.file.readstring(40) - else: - self.charcoding = None - - if self.lh > 12: - assert self.lh > 16, "inconsistency in TFM file: incomplete field" - self.fontfamily = self.file.readstring(20) - else: - self.fontfamily = None - - if debug: - print("(FAMILY %s)" % self.fontfamily) - print("(CODINGSCHEME %s)" % self.charcoding) - print("(DESINGSIZE R %f)" % (16.0*self.designsize/16777216)) - - if self.lh > 17: - self.sevenbitsave = self.file.readuchar() - # ignore the following two bytes - self.file.readint16() - facechar = self.file.readuchar() - # decode ugly face specification into the Knuth suggested string - if facechar < 18: - if facechar >= 12: - self.face = "E" - facechar -= 12 - elif facechar >= 6: - self.face = "C" - facechar -= 6 - else: - self.face = "R" - - if facechar >= 4: - self.face = "L" + self.face - facechar -= 4 - elif facechar >= 2: - self.face = "B" + self.face - facechar -= 2 - else: - self.face = "M" + self.face - - if facechar == 1: - self.face = self.face[0] + "I" + self.face[1] - else: - self.face = self.face[0] + "R" + self.face[1] - - else: - self.face = None - else: - self.sevenbitsave = self.face = None - - if self.lh > 18: - # just ignore the rest - print(self.file.read((self.lh-18)*4)) - - # - # read char_info - # - - self.char_info = [None]*(self.ec+1) - for charcode in range(self.bc, self.ec+1): - self.char_info[charcode] = char_info_word(self.file.readint32()) - if self.char_info[charcode].width_index == 0: - # disable character if width_index is zero - self.char_info[charcode] = None - - # - # read widths - # - - self.width = [None for width_index in range(self.nw)] - for width_index in range(self.nw): - self.width[width_index] = self.file.readint32() - - # - # read heights - # - - self.height = [None for height_index in range(self.nh)] - for height_index in range(self.nh): - self.height[height_index] = self.file.readint32() - - # - # read depths - # - - self.depth = [None for depth_index in range(self.nd)] - for depth_index in range(self.nd): - self.depth[depth_index] = self.file.readint32() - - # - # read italic - # - - self.italic = [None for italic_index in range(self.ni)] - for italic_index in range(self.ni): - self.italic[italic_index] = self.file.readint32() - - # - # read lig_kern - # - - # XXX decode to lig_kern_command - - self.lig_kern = [None for lig_kern_index in range(self.nl)] - for lig_kern_index in range(self.nl): - self.lig_kern[lig_kern_index] = self.file.readint32() - - # - # read kern - # - - self.kern = [None for kern_index in range(self.nk)] - for kern_index in range(self.nk): - self.kern[kern_index] = self.file.readint32() - - # - # read exten - # - - # XXX decode to extensible_recipe - - self.exten = [None for exten_index in range(self.ne)] - for exten_index in range(self.ne): - self.exten[exten_index] = self.file.readint32() - - # - # read param - # - - # XXX decode - - self.param = [None for param_index in range(self.np)] - for param_index in range(self.np): - self.param[param_index] = self.file.readint32() - - self.file.close() +# -*- encoding: utf-8 -*- +# +# +# Copyright (C) 2007-2011 Jörg Lehmann +# Copyright (C) 2007-2011 André Wobst +# +# This file is part of PyX (http://pyx.sourceforge.net/). +# +# PyX is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# PyX is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PyX; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + + +from pyx import reader + +class char_info_word: + + def __init__(self, word): + self.width_index = int((word & 0xFF000000) >> 24) #make sign-safe + self.height_index = (word & 0x00F00000) >> 20 + self.depth_index = (word & 0x000F0000) >> 16 + self.italic_index = (word & 0x0000FC00) >> 10 + self.tag = (word & 0x00000300) >> 8 + self.remainder = (word & 0x000000FF) + + +class TFMfile: + + def __init__(self, file, debug=0): + with reader.bytesreader(file.read()) as file: + + # + # read pre header + # + + self.lf = file.readint16() + self.lh = file.readint16() + self.bc = file.readint16() + self.ec = file.readint16() + self.nw = file.readint16() + self.nh = file.readint16() + self.nd = file.readint16() + self.ni = file.readint16() + self.nl = file.readint16() + self.nk = file.readint16() + self.ne = file.readint16() + self.np = file.readint16() + + if not (self.bc-1 <= self.ec <= 255 and + self.ne <= 256 and + self.lf == 6+self.lh+(self.ec-self.bc+1)+self.nw+self.nh+self.nd + +self.ni+self.nl+self.nk+self.ne+self.np): + raise RuntimeError("error in TFM pre-header") + + if debug: + print("lh=%d" % self.lh) + + # + # read header + # + + self.checksum = file.readint32() + self.designsize = file.readint32() + assert self.designsize > 0, "invald design size" + if self.lh > 2: + assert self.lh > 11, "inconsistency in TFM file: incomplete field" + self.charcoding = file.readstring(40) + else: + self.charcoding = None + + if self.lh > 12: + assert self.lh > 16, "inconsistency in TFM file: incomplete field" + self.fontfamily = file.readstring(20) + else: + self.fontfamily = None + + if debug: + print("(FAMILY %s)" % self.fontfamily) + print("(CODINGSCHEME %s)" % self.charcoding) + print("(DESINGSIZE R %f)" % (16.0*self.designsize/16777216)) + + if self.lh > 17: + self.sevenbitsave = file.readuchar() + # ignore the following two bytes + file.readint16() + facechar = file.readuchar() + # decode ugly face specification into the Knuth suggested string + if facechar < 18: + if facechar >= 12: + self.face = "E" + facechar -= 12 + elif facechar >= 6: + self.face = "C" + facechar -= 6 + else: + self.face = "R" + + if facechar >= 4: + self.face = "L" + self.face + facechar -= 4 + elif facechar >= 2: + self.face = "B" + self.face + facechar -= 2 + else: + self.face = "M" + self.face + + if facechar == 1: + self.face = self.face[0] + "I" + self.face[1] + else: + self.face = self.face[0] + "R" + self.face[1] + + else: + self.face = None + else: + self.sevenbitsave = self.face = None + + if self.lh > 18: + # just ignore the rest + print(file.read((self.lh-18)*4)) + + # + # read char_info + # + + self.char_info = [None]*(self.ec+1) + for charcode in range(self.bc, self.ec+1): + self.char_info[charcode] = char_info_word(file.readint32()) + if self.char_info[charcode].width_index == 0: + # disable character if width_index is zero + self.char_info[charcode] = None + + # + # read widths + # + + self.width = [None for width_index in range(self.nw)] + for width_index in range(self.nw): + self.width[width_index] = file.readint32() + + # + # read heights + # + + self.height = [None for height_index in range(self.nh)] + for height_index in range(self.nh): + self.height[height_index] = file.readint32() + + # + # read depths + # + + self.depth = [None for depth_index in range(self.nd)] + for depth_index in range(self.nd): + self.depth[depth_index] = file.readint32() + + # + # read italic + # + + self.italic = [None for italic_index in range(self.ni)] + for italic_index in range(self.ni): + self.italic[italic_index] = file.readint32() + + # + # read lig_kern + # + + # XXX decode to lig_kern_command + + self.lig_kern = [None for lig_kern_index in range(self.nl)] + for lig_kern_index in range(self.nl): + self.lig_kern[lig_kern_index] = file.readint32() + + # + # read kern + # + + self.kern = [None for kern_index in range(self.nk)] + for kern_index in range(self.nk): + self.kern[kern_index] = file.readint32() + + # + # read exten + # + + # XXX decode to extensible_recipe + + self.exten = [None for exten_index in range(self.ne)] + for exten_index in range(self.ne): + self.exten[exten_index] = file.readint32() + + # + # read param + # + + # XXX decode + + self.param = [None for param_index in range(self.np)] + for param_index in range(self.np): + self.param[param_index] = file.readint32() diff --git a/pyx/dvi/vffile.py b/pyx/dvi/vffile.py index d1eda5fd..04cdb56c 100644 --- a/pyx/dvi/vffile.py +++ b/pyx/dvi/vffile.py @@ -102,8 +102,6 @@ class vffile: else: raise VFError - afile.close() - def getfonts(self): return self.fonts diff --git a/pyx/epsfile.py b/pyx/epsfile.py index 34aca0e2..bd7e9aed 100644 --- a/pyx/epsfile.py +++ b/pyx/epsfile.py @@ -132,9 +132,6 @@ class linefilereader: self.buffer = self.buffer[eol:] return result - def close(self): - self.file.close() - def _readbbox(file): """returns bounding box of EPS file filename""" @@ -249,9 +246,8 @@ class epsfile(baseclasses.canvasitem): if bbox: self.mybbox = bbox else: - epsfile = self.open() - self.mybbox = _readbbox(epsfile) - epsfile.close() + with self.open() as epsfile: + self.mybbox = _readbbox(epsfile) # determine scaling in x and y direction self.scalex = self.scaley = scale @@ -334,9 +330,8 @@ class epsfile(baseclasses.canvasitem): file.write("%%%%BeginDocument: %s\n" % self.filename) - epsfile = self.open() - file.write_bytes(epsfile.read()) - epsfile.close() + with self.open() as epsfile: + file.write_bytes(epsfile.read()) file.write("%%EndDocument\n") file.write("EndEPSF\n") diff --git a/pyx/font/t1file.py b/pyx/font/t1file.py index b26fedbc..1f8d45dd 100644 --- a/pyx/font/t1file.py +++ b/pyx/font/t1file.py @@ -1174,9 +1174,8 @@ def from_PFA_bytes(bytes): def from_PFA_filename(filename): """create a T1file instance from PFA font file of given name""" - file = open(filename, "rb") - t1file = from_PFA_bytes(file.read()) - file.close() + with open(filename, "rb") as file: + t1file = from_PFA_bytes(file.read()) return t1file def from_PFB_bytes(bytes): @@ -1223,9 +1222,8 @@ def from_PFB_bytes(bytes): def from_PFB_filename(filename): """create a T1file instance from PFB font file of given name""" - file = open(filename, "rb") - t1file = from_PFB_bytes(file.read()) - file.close() + with open(filename, "rb") as file: + t1file = from_PFB_bytes(file.read()) return t1file def from_PF_bytes(bytes): @@ -1236,7 +1234,6 @@ def from_PF_bytes(bytes): def from_PF_filename(filename): """create a T1file instance from PFA or PFB font file of given name""" - file = open(filename, "rb") - t1file = from_PF_bytes(file.read()) - file.close() + with open(filename, "rb") as file: + t1file = from_PF_bytes(file.read()) return t1file diff --git a/pyx/graph/data.py b/pyx/graph/data.py index 06d1768d..05e0516c 100644 --- a/pyx/graph/data.py +++ b/pyx/graph/data.py @@ -323,9 +323,8 @@ class file(data): # not a file-like object -> open it cachekey = self.getcachekey(filename, commentpattern, stringpattern, columnpattern, skiphead, skiptail, every) if cachekey not in filecache: - f = open(filename) - filecache[cachekey] = readfile(f, filename) - f.close() + with open(filename) as f: + filecache[cachekey] = readfile(f, filename) data.__init__(self, filecache[cachekey], **kwargs) else: data.__init__(self, readfile(filename, "user provided file-like object"), **kwargs) diff --git a/pyx/pattern.py b/pyx/pattern.py index c29e946a..7ff70f16 100644 --- a/pyx/pattern.py +++ b/pyx/pattern.py @@ -73,7 +73,6 @@ class pattern(canvas.canvas, attr.exclusiveattr, style.fillstyle): realpatternbbox = bboxmodule.empty() canvas.canvas.processPS(self, patternfile, writer, pswriter.context(), registry, realpatternbbox) patternproc = patternfile.file.getvalue() - patternfile.close() if self.xstep is None: xstep = unit.topt(realpatternbbox.width()) @@ -114,7 +113,6 @@ class pattern(canvas.canvas, attr.exclusiveattr, style.fillstyle): realpatternbbox = bboxmodule.empty() canvas.canvas.processPDF(self, patternfile, writer, pdfwriter.context(), patternregistry, realpatternbbox) patternproc = patternfile.file.getvalue() - patternfile.close() registry.mergeregistry(patternregistry) diff --git a/pyx/pdfwriter.py b/pyx/pdfwriter.py index 7819f010..74d9cd79 100644 --- a/pyx/pdfwriter.py +++ b/pyx/pdfwriter.py @@ -266,7 +266,6 @@ class PDFcontent(PDFobject): acontext = context() page.processPDF(contentfile, awriter, acontext, registry, self.bbox) self.content = contentfile.file.getvalue() - contentfile.close() def write(self, file, awriter, registry): if awriter.compress: @@ -319,7 +318,6 @@ class PDFwriter: file = writer.writer(file) file.write_bytes(b"%PDF-1.4\n%\xc3\xb6\xc3\xa9\n") registry.write(file, self, catalog) - file.close() def getfontmap(self): if self._fontmap is None: diff --git a/pyx/pswriter.py b/pyx/pswriter.py index e5593e8e..166707d4 100644 --- a/pyx/pswriter.py +++ b/pyx/pswriter.py @@ -153,7 +153,6 @@ class EPSwriter(_PSwriter): file.write("%%EndProlog\n") file.write_bytes(pagefile.file.getvalue()) - pagefile.close() file.write("showpage\n") file.write("%%Trailer\n") @@ -197,7 +196,6 @@ class PSwriter(_PSwriter): pagesfile.write("%%EndPageSetup\n") pagesfile.write_bytes(pagefile.file.getvalue()) - pagefile.close() pagesfile.write("pgsave restore\n") pagesfile.write("showpage\n") pagesfile.write("%%PageTrailer\n") @@ -245,7 +243,6 @@ class PSwriter(_PSwriter): #file.write("%%EndSetup\n") file.write_bytes(pagesfile.file.getvalue()) - pagesfile.close() file.write("%%Trailer\n") file.write("%%EOF\n") diff --git a/pyx/reader.py b/pyx/reader.py index 27791f8c..839000e0 100644 --- a/pyx/reader.py +++ b/pyx/reader.py @@ -29,9 +29,6 @@ class reader: def __init__(self, filename): self.file = open(filename, "rb") - def close(self): - self.file.close() - def tell(self): return self.file.tell() @@ -82,6 +79,15 @@ class reader: assert l <= bytes-1, "inconsistency in file: string too long" return self.file.read(bytes-1)[:l] + def close(self): + self.file.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + return self.file.__exit__(exc_type, exc_value, traceback) + class bytesreader(reader): diff --git a/pyx/text.py b/pyx/text.py index 73a31173..4fbca434 100644 --- a/pyx/text.py +++ b/pyx/text.py @@ -903,9 +903,9 @@ class texrunner: os.rename(usefile, self.texfilename + usefile[extpos:]) except OSError: pass - texfile = open("%s.tex" % self.texfilename, "w") # start with filename -> creates dvi file with that name - texfile.write("\\relax%\n") - texfile.close() + with open("%s.tex" % self.texfilename, "w") as texfile: + # start with filename -> creates dvi file with that name + texfile.write("\\relax%\n") if self.texipc: ipcflag = " --ipc" else: @@ -957,20 +957,16 @@ class texrunner: if self.lfs: if not self.lfs.endswith(".lfs"): self.lfs = "%s.lfs" % self.lfs - lfsfile = config.open(self.lfs, []) - lfsdef = lfsfile.read().decode("ascii") - lfsfile.close() + with config.open(self.lfs, []) as lfsfile: + lfsdef = lfsfile.read().decode("ascii") self.execute(lfsdef, []) self.execute("\\normalsize%\n", []) self.execute("\\newdimen\\linewidth\\newdimen\\textwidth%\n", []) elif self.mode == "latex": if self.pyxgraphics: - pyxdef = config.open("pyx.def", []) pyxdef_filename = self.texfilename + ".pyx.def" - pyxdef_file = open(pyxdef_filename, "wb") - pyxdef_file.write(pyxdef.read()) - pyxdef.close() - pyxdef_file.close() + with config.open("pyx.def", []) as pyxdef, open(pyxdef_filename, "wb") as pyxdef_file: + pyxdef_file.write(pyxdef.read()) pyxdef_filename_tex = os.path.abspath(pyxdef_filename).replace(os.sep, "/") self.execute("\\makeatletter%\n" "\\let\\saveProcessOptions=\\ProcessOptions%\n" diff --git a/pyx/writer.py b/pyx/writer.py index 2d7f26b2..b2369a5e 100644 --- a/pyx/writer.py +++ b/pyx/writer.py @@ -36,5 +36,8 @@ class writer: def tell(self): return self.file.tell() - def close(self): - self.file.close() + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + return self.file.__exit__(exc_type, exc_value, traceback) -- 2.11.4.GIT