From 29bfd9ecc45b1a0e539fc98e10ea3feeb390ad83 Mon Sep 17 00:00:00 2001 From: bretello Date: Thu, 24 Feb 2022 11:11:16 +0100 Subject: [PATCH] use context manager to open files --- grc | 22 +++++++++++----------- grcat | 49 +++++++++++++++++++++++++------------------------ 2 files changed, 36 insertions(+), 35 deletions(-) diff --git a/grc b/grc index 4b6848b..02baa6c 100755 --- a/grc +++ b/grc @@ -95,17 +95,17 @@ if cfile == "": for conffile in conffilenames: # test if conffile exists, it can be also a pipe if os.path.exists(conffile) and not os.path.isdir(conffile): - f = open(conffile, "r") - while 1: - l = f.readline() - if l == "": - break - if l[0] == "#" or l[0] == '\012': - continue - regexp = l.strip() - if re.search(regexp, ' '.join(args)): - cfile = f.readline().strip() - break + with open(conffile, "r", encoding='UTF-8') as f: + while 1: + l = f.readline() + if l == "": + break + if l[0] == "#" or l[0] == '\012': + continue + regexp = l.strip() + if re.search(regexp, ' '.join(args)): + cfile = f.readline().strip() + break signal.signal(signal.SIGINT, catch_signal) diff --git a/grcat b/grcat index 3a0d054..7f265b6 100755 --- a/grcat +++ b/grcat @@ -147,36 +147,37 @@ if not conffile: regexplist = [] -f = open(conffile, "r") is_last = 0 split = str.split lower = str.lower letters = string.ascii_letters while not is_last: ll = {'count':"more"} - while 1: - l = f.readline() - if l == "": - is_last = 1 - break - if l[0] == "#" or l[0] == '\012': - continue - if not l[0] in letters: - break - fields = split(l.rstrip('\r\n'), "=", 1) - if len(fields) != 2: - sys.stderr.write('Error in configuration, I expect keyword=value line\n') - sys.stderr.write('But I got instead:\n') - sys.stderr.write(repr(l)) - sys.stderr.write('\n') - sys.exit(1) - keyword, value = fields - keyword = lower(keyword) - if keyword in ('colors', 'colour', 'color'): - keyword = 'colours' - if not keyword in ["regexp", "colours", "count", "command", "skip", "replace", "concat"]: - raise ValueError("Invalid keyword") - ll[keyword] = value + + with open(conffile, "r", encoding='UTF-8') as f: + while 1: + l = f.readline() + if l == "": + is_last = 1 + break + if l[0] == "#" or l[0] == '\012': + continue + if not l[0] in letters: + break + fields = split(l.rstrip('\r\n'), "=", 1) + if len(fields) != 2: + sys.stderr.write('Error in configuration, I expect keyword=value line\n') + sys.stderr.write('But I got instead:\n') + sys.stderr.write(repr(l)) + sys.stderr.write('\n') + sys.exit(1) + keyword, value = fields + keyword = lower(keyword) + if keyword in ('colors', 'colour', 'color'): + keyword = 'colours' + if not keyword in ["regexp", "colours", "count", "command", "skip", "replace", "concat"]: + raise ValueError("Invalid keyword") + ll[keyword] = value # Split string into one string per regex group # e.g. split "brown bold, red" into "brown bold" and