diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index 67e7561c4e7..625a89bfa02 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -883,25 +883,24 @@ def GetWindow(self): env["GISDBASE"], env["LOCATION_NAME"], env["MAPSET"], "WIND" ) try: - windfile = open(filename) + with open(filename) as windfile: + for line in windfile: + line = line.strip() + try: + key, value = line.split(":", 1) + except ValueError as e: + sys.stderr.write( + _("\nERROR: Unable to read WIND file: %s\n") % e + ) + return None + + self.wind[key.strip()] = value.strip() except OSError as e: sys.exit( _("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % {"file": filename, "ret": e} ) - for line in windfile: - line = line.strip() - try: - key, value = line.split(":", 1) - except ValueError as e: - sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e) - return None - - self.wind[key.strip()] = value.strip() - - windfile.close() - return self.wind def AdjustRegion(self): diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index aa51f8fb207..53deec8a6bf 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -29,6 +29,7 @@ from core import globalvar from core.gcmd import GException, GError from core.utils import GetSettingsPath, PathJoin, rgb2str +from pathlib import Path class SettingsJSONEncoder(json.JSONEncoder): @@ -104,7 +105,8 @@ def __init__(self): def _generateLocale(self): """Generate locales""" try: - self.locs = os.listdir(os.path.join(os.environ["GISBASE"], "locale")) + locale_path = Path(os.environ["GISBASE"]) / "locale" + self.locs = [p.name for p in locale_path.iterdir() if p.is_dir()] self.locs.append("en") # GRASS doesn't ship EN po files self.locs.sort() # Add a default choice to not override system locale @@ -941,30 +943,28 @@ def _readLegacyFile(self, settings=None): settings = self.userSettings try: - fd = open(self.legacyFilePath) + with open(self.legacyFilePath) as fd: + line = "" + for line in fd: + line = line.rstrip("%s" % os.linesep) + group, key = line.split(self.sep)[0:2] + kv = line.split(self.sep)[2:] + subkeyMaster = None + if len(kv) % 2 != 0: # multiple (e.g. nviz) + subkeyMaster = kv[0] + del kv[0] + idx = 0 + while idx < len(kv): + subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx] + value = kv[idx + 1] + value = self._parseValue(value, read=True) + self.Append(settings, group, key, subkey, value) + idx += 2 except OSError: sys.stderr.write( _("Unable to read settings file <%s>\n") % self.legacyFilePath ) return - - try: - line = "" - for line in fd: - line = line.rstrip("%s" % os.linesep) - group, key = line.split(self.sep)[0:2] - kv = line.split(self.sep)[2:] - subkeyMaster = None - if len(kv) % 2 != 0: # multiple (e.g. nviz) - subkeyMaster = kv[0] - del kv[0] - idx = 0 - while idx < len(kv): - subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx] - value = kv[idx + 1] - value = self._parseValue(value, read=True) - self.Append(settings, group, key, subkey, value) - idx += 2 except ValueError as e: print( _( @@ -975,9 +975,6 @@ def _readLegacyFile(self, settings=None): % {"file": self.legacyFilePath, "detail": e, "line": line}, file=sys.stderr, ) - fd.close() - - fd.close() def SaveToFile(self, settings=None): """Save settings to the file""" diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index a1722fec64b..6af82e7d1cc 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -828,7 +828,21 @@ def StoreEnvVariable(key, value=None, envFile=None): lineSkipped = [] if os.path.exists(envFile): try: - fd = open(envFile) + with open(envFile) as fd: + for line in fd: + line = line.rstrip(os.linesep) + try: + k, v = (x.strip() for x in line.split(" ", 1)[1].split("=", 1)) + except Exception as e: + sys.stderr.write( + _("%s: line skipped - unable to parse '%s'\nReason: %s\n") + % (envFile, line, e) + ) + lineSkipped.append(line) + continue + if k in environ: + sys.stderr.write(_("Duplicated key: %s\n") % k) + environ[k] = v except OSError as error: sys.stderr.write( _("Unable to open file '{name}': {error}\n").format( @@ -836,22 +850,6 @@ def StoreEnvVariable(key, value=None, envFile=None): ) ) return - for line in fd: - line = line.rstrip(os.linesep) - try: - k, v = (x.strip() for x in line.split(" ", 1)[1].split("=", 1)) - except Exception as e: - sys.stderr.write( - _("%s: line skipped - unable to parse '%s'\nReason: %s\n") - % (envFile, line, e) - ) - lineSkipped.append(line) - continue - if k in environ: - sys.stderr.write(_("Duplicated key: %s\n") % k) - environ[k] = v - - fd.close() # update environmental variables if value is None: @@ -861,7 +859,15 @@ def StoreEnvVariable(key, value=None, envFile=None): # write update env file try: - fd = open(envFile, "w") + with open(envFile, "w") as fd: + expCmd = "set" if windows else "export" + + fd.writelines( + "%s %s=%s\n" % (expCmd, key, value) for key, value in environ.items() + ) + + # write also skipped lines + fd.writelines(line + os.linesep for line in lineSkipped) except OSError as error: sys.stderr.write( _("Unable to create file '{name}': {error}\n").format( @@ -869,14 +875,6 @@ def StoreEnvVariable(key, value=None, envFile=None): ) ) return - expCmd = "set" if windows else "export" - - fd.writelines("%s %s=%s\n" % (expCmd, key, value) for key, value in environ.items()) - - # write also skipped lines - fd.writelines(line + os.linesep for line in lineSkipped) - - fd.close() def SetAddOnPath(addonPath=None, key="PATH"): diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py index bd09a9354a6..300e9993f5e 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -1730,7 +1730,11 @@ def read(self, parent): :return: list of map layers """ try: - file = open(self.filename) + with open(self.filename) as file: # Changed to context manager + line_id = 1 + for line in file: + self.process_line(line.rstrip("\n"), line_id) + line_id += 1 except OSError: wx.MessageBox( parent=parent, @@ -1740,13 +1744,6 @@ def read(self, parent): ) return [] - line_id = 1 - for line in file: - self.process_line(line.rstrip("\n"), line_id) - line_id += 1 - - file.close() - if self.num_error > 0: wx.MessageBox( parent=parent, diff --git a/pyproject.toml b/pyproject.toml index 69bbc9a0249..9240dada2b3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -268,11 +268,6 @@ ignore = [ # Other ignores: "**.py" = ["PYI066"] "*/testsuite/**.py" = ["PT009", "PT027"] -"gui/wxpython/core/globalvar.py" = ["PTH208"] -"gui/wxpython/core/render.py" = ["SIM115"] -"gui/wxpython/core/settings.py" = ["PTH208", "SIM115"] -"gui/wxpython/core/utils.py" = ["SIM115"] -"gui/wxpython/core/workspace.py" = ["SIM115"] "gui/wxpython/datacatalog/catalog.py" = ["PTH208"] "gui/wxpython/dbmgr/base.py" = ["SIM115"] "gui/wxpython/gcp/manager.py" = ["PTH208"]