From dd2a5c4a353d0feb6b7c1dbf081643a57f85fde5 Mon Sep 17 00:00:00 2001 From: Vassilii Khachaturov Date: Thu, 26 Dec 2013 18:45:18 +0200 Subject: [PATCH] 7327: clean up file open/lock/close code In preparation for fixing the bug, discovered minor glitches in the open/lock/close logic on error paths. Using the RAII syntax for xml_file and removing redundant unlock-before-close. --- src/RecentFiles.py | 57 +++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/src/RecentFiles.py b/src/RecentFiles.py index f436edbae..dea9088e7 100644 --- a/src/RecentFiles.py +++ b/src/RecentFiles.py @@ -162,25 +162,23 @@ class RecentFiles(object): """ Saves the current GRAMPS RecentFiles collection to the associated file. """ - xml_file = file(os.path.expanduser(GRAMPS_FILENAME),'w') - if use_lock: - fcntl.lockf(xml_file,fcntl.LOCK_EX) - xml_file.write("\n") - xml_file.write('\n') - index = 0 - for item in self.gramps_recent_files: - index += 1 - if index > MAX_GRAMPS_ITEMS: - break - xml_file.write(' \n') - xml_file.write(' \n' % item.get_path()) - xml_file.write(' \n' % item.get_name()) - xml_file.write(' %d\n' % item.get_time()) - xml_file.write(' \n') - xml_file.write('\n') - if use_lock: - fcntl.lockf(xml_file,fcntl.LOCK_UN) - xml_file.close() + with open(os.path.expanduser(GRAMPS_FILENAME), 'w') as xml_file: + if use_lock: + fcntl.lockf(xml_file,fcntl.LOCK_EX) + xml_file.write("\n") + xml_file.write('\n') + index = 0 + for item in self.gramps_recent_files: + index += 1 + if index > MAX_GRAMPS_ITEMS: + break + xml_file.write(' \n') + xml_file.write(' \n' % item.get_path()) + xml_file.write(' \n' % item.get_name()) + xml_file.write(' %d\n' % item.get_time()) + xml_file.write(' \n') + xml_file.write('\n') + # all advisory locks on a file are released on close #------------------------------------------------------------------------- # @@ -196,19 +194,16 @@ class RecentParser(object): self.recent_files = [] try: - xml_file = open(os.path.expanduser(GRAMPS_FILENAME)) - if use_lock: - fcntl.lockf(xml_file,fcntl.LOCK_SH) + with open(os.path.expanduser(GRAMPS_FILENAME)) as xml_file: + if use_lock: + fcntl.lockf(xml_file,fcntl.LOCK_SH) - p = ParserCreate() - p.StartElementHandler = self.startElement - p.EndElementHandler = self.endElement - p.CharacterDataHandler = self.characters - p.ParseFile(xml_file) - - if use_lock: - fcntl.lockf(xml_file,fcntl.LOCK_UN) - xml_file.close() + p = ParserCreate() + p.StartElementHandler = self.startElement + p.EndElementHandler = self.endElement + p.CharacterDataHandler = self.characters + p.ParseFile(xml_file) + # all advisory locks on a file are released on close except: pass