From 607e064bfb45b768c5fce74d6509cce1ec371f94 Mon Sep 17 00:00:00 2001 From: Louis Date: Sat, 22 Nov 2014 11:02:13 +0100 Subject: [PATCH] Transformation de encoding.open_read en un 'context manager' --- patacrep/content/include.py | 7 ++----- patacrep/encoding.py | 8 ++++++-- patacrep/index.py | 6 +----- patacrep/latex/__init__.py | 3 ++- patacrep/songbook.py | 8 ++------ patacrep/templates.py | 41 ++++++++++++++++--------------------- 6 files changed, 31 insertions(+), 42 deletions(-) diff --git a/patacrep/content/include.py b/patacrep/content/include.py index dcc969a9..9fc73621 100644 --- a/patacrep/content/include.py +++ b/patacrep/content/include.py @@ -48,15 +48,12 @@ def parse(keyword, config, argument, contentlist): filepath = load_from_datadirs(path, config) content_file = None try: - content_file = encoding.open_read(filepath, 'r') - new_content = json.load(content_file) + with encoding.open_read(filepath, 'r') as content_file: + new_content = json.load(content_file) except Exception as error: # pylint: disable=broad-except LOGGER.error(error) LOGGER.error("Error while loading file '{}'.".format(filepath)) sys.exit(1) - finally: - if content_file: - content_file.close() config["datadir"].append(os.path.abspath(os.path.dirname(filepath))) new_contentlist += process_content(new_content, config) diff --git a/patacrep/encoding.py b/patacrep/encoding.py index ca917295..a1084aa8 100644 --- a/patacrep/encoding.py +++ b/patacrep/encoding.py @@ -5,17 +5,21 @@ import codecs import chardet import logging +import contextlib LOGGER = logging.getLogger(__name__) + +@contextlib.contextmanager def open_read(filename, mode='r'): """Open a file for reading, guessing the right encoding. Return a fileobject, reading unicode strings. """ - return codecs.open( + with codecs.open( filename, mode=mode, encoding=chardet.detect(open(filename, 'rb').read())['encoding'], errors='replace', - ) + ) as fileobject: + yield fileobject diff --git a/patacrep/index.py b/patacrep/index.py index c715918a..f111f059 100644 --- a/patacrep/index.py +++ b/patacrep/index.py @@ -29,13 +29,9 @@ def process_sxd(filename): """ data = [] index_file = None - try: - index_file = encoding.open_read(filename, 'r') + with encoding.open_read(filename, 'r') as index_file: for line in index_file: data.append(line.strip()) - finally: - if index_file: - index_file.close() i = 1 idx = Index(data[0]) diff --git a/patacrep/latex/__init__.py b/patacrep/latex/__init__.py index fce5470f..f923b822 100644 --- a/patacrep/latex/__init__.py +++ b/patacrep/latex/__init__.py @@ -15,6 +15,7 @@ def parsesong(path): """Return a dictonary of data read from the latex file `path`. """ - data = syntax_parsesong(encoding.open_read(path).read(), path) + with encoding.open_read(path) as songfile: + data = syntax_parsesong(songfile.read(), path) data['@path'] = path return data diff --git a/patacrep/songbook.py b/patacrep/songbook.py index e3bcf555..dfa21651 100755 --- a/patacrep/songbook.py +++ b/patacrep/songbook.py @@ -100,17 +100,13 @@ def main(): basename = os.path.basename(songbook_path)[:-3] - songbook_file = None try: - songbook_file = encoding.open_read(songbook_path) - songbook = json.load(songbook_file) + with encoding.open_read(songbook_path) as songbook_file: + songbook = json.load(songbook_file) except Exception as error: # pylint: disable=broad-except LOGGER.error(error) LOGGER.error("Error while loading file '{}'.".format(songbook_path)) sys.exit(1) - finally: - if songbook_file: - songbook_file.close() # Gathering datadirs datadirs = [] diff --git a/patacrep/templates.py b/patacrep/templates.py index d1e9a616..55a354fb 100644 --- a/patacrep/templates.py +++ b/patacrep/templates.py @@ -186,32 +186,27 @@ class TexRenderer(object): """ subvariables = {} - template_file = None templatename = self.texenv.get_template(template).filename - try: - template_file = encoding.open_read(templatename, 'r') + with encoding.open_read(templatename, 'r') as template_file: content = template_file.read() - subtemplates = list(find_templates(self.texenv.parse(content))) - match = re.findall(_VARIABLE_REGEXP, content) - if match: - for var in match: - try: - subvariables.update(json.loads(var)) - except ValueError as exception: - raise errors.TemplateError( - exception, - ( - "Error while parsing json in file " - "{filename}. The json string was:" - "\n'''\n{jsonstring}\n'''" - ).format( - filename=templatename, - jsonstring=var, - ) + subtemplates = list(find_templates(self.texenv.parse(content))) + match = re.findall(_VARIABLE_REGEXP, content) + if match: + for var in match: + try: + subvariables.update(json.loads(var)) + except ValueError as exception: + raise errors.TemplateError( + exception, + ( + "Error while parsing json in file " + "{filename}. The json string was:" + "\n'''\n{jsonstring}\n'''" + ).format( + filename=templatename, + jsonstring=var, ) - finally: - if template_file: - template_file.close() + ) return (subvariables, subtemplates)