From 2b60b99c4e93a473cd62265c32291d6e329371ec Mon Sep 17 00:00:00 2001 From: mshukun Date: Tue, 28 May 2024 18:11:43 -0400 Subject: [PATCH 1/9] Fix E722 `do not use bare except` --- .flake8 | 108 +++++++----------- gui/wxpython/core/gconsole.py | 2 +- gui/wxpython/core/render.py | 2 +- gui/wxpython/core/settings.py | 4 +- gui/wxpython/core/toolboxes.py | 2 +- gui/wxpython/core/utils.py | 10 +- gui/wxpython/core/workspace.py | 6 +- gui/wxpython/dbmgr/base.py | 14 +-- gui/wxpython/dbmgr/dialogs.py | 2 +- gui/wxpython/dbmgr/manager.py | 2 +- gui/wxpython/dbmgr/sqlbuilder.py | 2 +- gui/wxpython/gcp/manager.py | 2 +- gui/wxpython/gui_core/dialogs.py | 4 +- gui/wxpython/gui_core/forms.py | 2 +- gui/wxpython/gui_core/ghelp.py | 14 +-- gui/wxpython/gui_core/gselect.py | 2 +- gui/wxpython/gui_core/widgets.py | 2 +- gui/wxpython/image2target/ii2t_gis_set.py | 8 +- gui/wxpython/image2target/ii2t_manager.py | 2 +- gui/wxpython/iscatt/controllers.py | 4 +- gui/wxpython/iscatt/frame.py | 2 +- gui/wxpython/lmgr/frame.py | 12 +- gui/wxpython/lmgr/layertree.py | 8 +- gui/wxpython/location_wizard/wizard.py | 18 +-- gui/wxpython/mapdisp/main.py | 2 +- gui/wxpython/mapwin/base.py | 6 +- gui/wxpython/mapwin/buffered.py | 14 +-- gui/wxpython/mapwin/graphics.py | 2 +- gui/wxpython/modules/colorrules.py | 4 +- gui/wxpython/modules/histogram.py | 4 +- gui/wxpython/modules/import_export.py | 2 +- gui/wxpython/modules/mcalc_builder.py | 6 +- gui/wxpython/nviz/mapwindow.py | 2 +- gui/wxpython/nviz/tools.py | 24 ++-- gui/wxpython/photo2image/ip2i_manager.py | 2 +- gui/wxpython/psmap/frame.py | 4 +- gui/wxpython/rlisetup/wizard.py | 2 +- gui/wxpython/startup/locdownload.py | 2 +- gui/wxpython/tplot/frame.py | 12 +- gui/wxpython/vdigit/dialogs.py | 2 +- gui/wxpython/vdigit/mapwindow.py | 10 +- gui/wxpython/vdigit/preferences.py | 2 +- gui/wxpython/wxplot/base.py | 4 +- gui/wxpython/wxplot/histogram.py | 2 +- gui/wxpython/wxplot/profile.py | 4 +- lib/init/grass.py | 10 +- locale/grass_po_stats.py | 2 +- man/build_keywords.py | 10 +- man/build_topics.py | 6 +- .../temporal/abstract_space_time_dataset.py | 4 +- .../grass/temporal/c_libraries_interface.py | 26 ++--- python/grass/temporal/core.py | 8 +- python/grass/temporal/datetime_math.py | 8 +- .../spatial_topology_dataset_connector.py | 14 +-- python/grass/temporal/temporal_algebra.py | 4 +- python/grass/temporal/temporal_granularity.py | 6 +- .../temporal/temporal_raster_base_algebra.py | 2 +- .../temporal_topology_dataset_connector.py | 22 ++-- scripts/d.frame/d.frame.py | 4 +- scripts/d.rast.edit/d.rast.edit.py | 2 +- scripts/i.pansharpen/i.pansharpen.py | 10 +- scripts/r.fillnulls/r.fillnulls.py | 8 +- scripts/r.in.srtm/r.in.srtm.py | 4 +- scripts/r.in.wms/srs.py | 2 +- scripts/r.in.wms/wms_drv.py | 2 +- scripts/r.in.wms/wms_gdal_drv.py | 2 +- scripts/v.import/v.import.py | 4 +- scripts/v.unpack/v.unpack.py | 2 +- scripts/v.what.strds/v.what.strds.py | 2 +- utils/gitlog2changelog.py | 4 +- 70 files changed, 247 insertions(+), 267 deletions(-) diff --git a/.flake8 b/.flake8 index 84c3826b32c..52ca99e5c05 100644 --- a/.flake8 +++ b/.flake8 @@ -20,9 +20,9 @@ per-file-ignores = # F841 local variable assigned to but never used # E741 ambiguous variable name 'l' __init__.py: F401, F403 - lib/init/grass.py: E722, F821, F841, W605 + lib/init/grass.py: F821, F841, W605 utils/mkrest.py: W605 - utils/gitlog2changelog.py: E722, E712, W605 + utils/gitlog2changelog.py: E712, W605 utils/g.html2man/ggroff.py: W605 man/build_check_rest.py: F403, F405 man/build_full_index_rest.py: F403, F405 @@ -33,65 +33,60 @@ per-file-ignores = man/build_full_index.py: F403, F405 man/build_index.py: F403, F405 man/build_index_rest.py: F403, F405 - man/build_keywords.py: F403, F405, E722 - man/build_topics.py: F403, F405, E722 + man/build_keywords.py: F403, F405 + man/build_topics.py: F403, F405 man/build_html.py: E501 imagery/i.atcorr/create_iwave.py: F632, F821, W293 doc/python/raster_example_ctypes.py: F403, F405 doc/python/vector_example_ctypes.py: F403, F405 doc/python/m.distance.py: F403, F405, E501 doc/gui/wxpython/example/dialogs.py: F401 - locale/grass_po_stats.py: E122, E128, E231, E401, E722, E741 + locale/grass_po_stats.py: E122, E128, E231, E401, E741 gui/scripts/d.wms.py: E501 gui/wxpython/core/gcmd.py: E402 gui/wxpython/core/gthread.py: F841 - gui/wxpython/core/gconsole.py: E722, W605 + gui/wxpython/core/gconsole.py: W605 gui/wxpython/core/globalvar.py: W605 - gui/wxpython/core/toolboxes.py: E722 - gui/wxpython/core/utils.py: E722, F841, W605 - gui/wxpython/core/workspace.py: E722 - gui/wxpython/core/render.py: E722, F841 + gui/wxpython/core/utils.py: F841, W605 + gui/wxpython/core/render.py: F841 gui/wxpython/core/ws.py: F841 - gui/wxpython/core/settings.py: E722 gui/wxpython/core/watchdog.py: E402 gui/wxpython/datacatalog/tree.py: E731, E402 - gui/wxpython/dbmgr/base.py: E722, F841 - gui/wxpython/dbmgr/dialogs.py: F841, E722 - gui/wxpython/dbmgr/sqlbuilder.py: E722, F841 - gui/wxpython/dbmgr/manager.py: E722 + gui/wxpython/dbmgr/base.py: F841 + gui/wxpython/dbmgr/dialogs.py: F841 + gui/wxpython/dbmgr/sqlbuilder.py: F841 gui/wxpython/dbmgr/vinfo.py: F841 gui/wxpython/docs/wxgui_sphinx/conf.py: E402, W291 gui/wxpython/gcp/g.gui.gcp.py: F841 - gui/wxpython/gcp/manager.py: F841, E722 + gui/wxpython/gcp/manager.py: F841 gui/wxpython/gcp/mapdisplay.py: F841 - gui/wxpython/gui_core/*: F841, E266, E722, W605 - gui/wxpython/gui_core/dialogs.py: E722, F841, W605 - gui/wxpython/gui_core/forms.py: E722, F841 - gui/wxpython/gui_core/ghelp.py: E722 - gui/wxpython/gui_core/gselect.py: F841, E266, E722 + gui/wxpython/gui_core/*: F841, E266, W605 + gui/wxpython/gui_core/dialogs.py: F841, W605 + gui/wxpython/gui_core/forms.py: F841 + gui/wxpython/gui_core/gselect.py: F841, E266 gui/wxpython/gui_core/preferences.py: E266, F841 gui/wxpython/gui_core/treeview.py: F841 - gui/wxpython/gui_core/widgets.py: F841, E722, E266 - gui/wxpython/image2target/*: F841, E722, E265 + gui/wxpython/gui_core/widgets.py: F841, E266 + gui/wxpython/image2target/*: F841, E265 gui/wxpython/image2target/g.gui.image2target.py: E501, E265, F841 - gui/wxpython/iscatt/*: F841, E722, E741, F405, F403 + gui/wxpython/iscatt/*: F841, E741, F405, F403 gui/wxpython/lmgr/giface.py: E741 - gui/wxpython/lmgr/frame.py: F841, E722, W605 + gui/wxpython/lmgr/frame.py: F841, W605 # layertree still includes some formatting issues (it is ignored by Black) - gui/wxpython/lmgr/layertree.py: E722, E266, W504, E225 + gui/wxpython/lmgr/layertree.py: E266, W504, E225 gui/wxpython/lmgr/workspace.py: F841 - gui/wxpython/modules/*: F841, E722, W605 - gui/wxpython/nviz/*: F841, E266, E722, W605, F403, F405 - gui/wxpython/photo2image/*: F841, E722, E265 + gui/wxpython/modules/*: F841, W605 + gui/wxpython/nviz/*: F841, E266, W605, F403, F405 + gui/wxpython/photo2image/*: F841, E265 gui/wxpython/photo2image/g.gui.photo2image.py: E501, F841 - gui/wxpython/psmap/*: F841, E266, E722, F405, F403 - gui/wxpython/vdigit/*: F841, E722, E741, F405, F403 + gui/wxpython/psmap/*: F841, E266, F405, F403 + gui/wxpython/vdigit/*: F841, E741, F405, F403 gui/wxpython/vnet/*: F841 gui/wxpython/wxgui.py: F841 gui/wxpython/animation/g.gui.animation.py: E501 gui/wxpython/animation/mapwindow.py: F841 gui/wxpython/animation/provider.py: F841 - gui/wxpython/tplot/frame.py: F841, E722, E741 + gui/wxpython/tplot/frame.py: F841, E741 gui/wxpython/tplot/g.gui.tplot.py: E501 gui/wxpython/rdigit/g.gui.rdigit.py: F841 gui/wxpython/iclass/dialogs.py: E741 @@ -99,27 +94,20 @@ per-file-ignores = gui/wxpython/iclass/frame.py: F405, F403 gui/wxpython/iclass/g.gui.iclass.py: E501 gui/wxpython/iclass/statistics.py: F841, F405, F403 - gui/wxpython/wxplot/histogram.py: E722 - gui/wxpython/wxplot/profile.py: F841, E722 - gui/wxpython/wxplot/base.py: F841, E722 + gui/wxpython/wxplot/profile.py: F841 + gui/wxpython/wxplot/base.py: F841 gui/wxpython/location_wizard/dialogs.py: F841 - gui/wxpython/location_wizard/wizard.py: E722 - gui/wxpython/mapdisp/main.py: E722 gui/wxpython/mapdisp/test_mapdisp.py: E501 gui/wxpython/mapdisp/statusbar.py: F841 gui/wxpython/mapswipe/g.gui.mapswipe.py: E501 - gui/wxpython/mapwin/base.py: E722 - gui/wxpython/mapwin/buffered.py: E722 - gui/wxpython/mapwin/graphics.py: E722 - gui/wxpython/startup/locdownload.py: E722, E402 + gui/wxpython/startup/locdownload.py: E402 gui/wxpython/timeline/g.gui.timeline.py: E501, E741 gui/wxpython/timeline/frame.py: E741 - gui/wxpython/tools/build_modules_xml.py: E722 gui/wxpython/web_services/cap_interface.py: E501 gui/wxpython/web_services/widgets.py: F841, E741, W605, E402 gui/wxpython/rlisetup/frame.py: E741 gui/wxpython/rlisetup/sampling_frame.py: F841 - gui/wxpython/rlisetup/wizard.py: E722, E741 + gui/wxpython/rlisetup/wizard.py: E741 # Generated file gui/wxpython/menustrings.py: E501 # F821 undefined name 'cmp' @@ -142,18 +130,15 @@ per-file-ignores = python/grass/pygrass/rpc/__init__.py: F401, F403 python/grass/pygrass/utils.py: E402 python/grass/script/task.py: W605 - python/grass/temporal/abstract_space_time_dataset.py: W605, F841, E722 - python/grass/temporal/c_libraries_interface.py: F841, E722 - python/grass/temporal/core.py: E722 - python/grass/temporal/datetime_math.py: F841, E722 + python/grass/temporal/abstract_space_time_dataset.py: W605, F841 + python/grass/temporal/c_libraries_interface.py: F841 + python/grass/temporal/datetime_math.py: F841 python/grass/temporal/open_stds.py: F841 - python/grass/temporal/spatial_topology_dataset_connector.py: E722 - python/grass/temporal/temporal_algebra.py: E741, F841, E722 - python/grass/temporal/temporal_granularity.py: F841, E722 + python/grass/temporal/temporal_algebra.py: E741, F841 + python/grass/temporal/temporal_granularity.py: F841 python/grass/temporal/temporal_raster_algebra.py: E741 - python/grass/temporal/temporal_raster_base_algebra.py: F841, E722 + python/grass/temporal/temporal_raster_base_algebra.py: F841 python/grass/temporal/temporal_raster3d_algebra.py: E741 - python/grass/temporal/temporal_topology_dataset_connector.py: E722 python/grass/temporal/temporal_vector_algebra.py: E741, F841 python/grass/temporal/univar_statistics.py: E231 # Current benchmarks/tests are changing sys.path before import. @@ -172,24 +157,19 @@ per-file-ignores = python/grass/*/*/*/__init__.py: F401, F403 # E402 module level import not at top of file scripts/d.polar/d.polar.py: F841 - scripts/r.in.wms/wms_gdal_drv.py: F841, E722 + scripts/r.in.wms/wms_gdal_drv.py: F841 scripts/r.in.wms/wms_cap_parsers.py: F841, E741 - scripts/r.in.wms/wms_drv.py: E402, E722 - scripts/r.in.wms/srs.py: E722 + scripts/r.in.wms/wms_drv.py: E402 scripts/r.semantic.label/r.semantic.label.py: F841, E501 scripts/v.report/v.report.py: F841, E721 scripts/db.out.ogr/db.out.ogr.py: F841 - scripts/g.extension/g.extension.py: F841, E722, E501 - scripts/v.unpack/v.unpack.py: F841, E722, E501 - scripts/v.import/v.import.py: F841, E722, E501 + scripts/g.extension/g.extension.py: F841, E501 + scripts/v.unpack/v.unpack.py: F841, E501 + scripts/v.import/v.import.py: F841, E501 scripts/db.univar/db.univar.py: E741, E501 scripts/d.rast.leg/d.rast.leg.py: E741 - scripts/d.frame/d.frame.py: E722 - scripts/i.pansharpen/i.pansharpen.py: E722, E501 - scripts/r.in.srtm/r.in.srtm.py: E722 - scripts/r.fillnulls/r.fillnulls.py: E722 - scripts/d.rast.edit/d.rast.edit.py: E722 - scripts/v.what.strds/v.what.strds.py: E722, E501 + scripts/i.pansharpen/i.pansharpen.py: E501 + scripts/v.what.strds/v.what.strds.py: E501 # Line too long (esp. module interface definitions) scripts/*/*.py: E501 # local variable 'column' is assigned to but never used diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index 4705d639297..ac7e07e57d5 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -676,7 +676,7 @@ def RunCmd( if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) - except: + except Exception: task = None else: task = None diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index 6e658252bbd..cd48ac24862 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -1242,7 +1242,7 @@ def SetRegion(self, windres=False, windres3=False): return grass_region - except: + except Exception: return None def GetListOfLayers( diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index ea3c2c1c738..b570bb810f7 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -110,7 +110,7 @@ def _generateLocale(self): self.locs.sort() # Add a default choice to not override system locale self.locs.insert(0, "system") - except: + except Exception: # No NLS self.locs = ["system"] @@ -992,7 +992,7 @@ def SaveToFile(self, settings=None): if not os.path.exists(dirPath): try: os.mkdir(dirPath) - except: + except Exception: GError(_("Unable to create settings directory")) return try: diff --git a/gui/wxpython/core/toolboxes.py b/gui/wxpython/core/toolboxes.py index 1d58d59f867..b75cc4438d9 100644 --- a/gui/wxpython/core/toolboxes.py +++ b/gui/wxpython/core/toolboxes.py @@ -208,7 +208,7 @@ def getMenudataFile(userRootFile, newFile, fallback): fh.write(xml) fh.close() return menudataFile - except: + except Exception: _debug( 2, ( diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index 9c42a77487e..1993193f5da 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -76,7 +76,7 @@ def GetTempfile(pref=None): return os.path.join(pref, file) else: return tempfile - except: + except Exception: return None @@ -254,7 +254,7 @@ def ListOfCatsToRange(cats): try: cats = list(map(int, cats)) - except: + except Exception: return catstr i = 0 @@ -579,7 +579,7 @@ def GetListOfLocations(dbase): os.path.join(location, "*") ): listOfLocations.append(os.path.basename(location)) - except: + except Exception: pass except (UnicodeEncodeError, UnicodeDecodeError) as e: raise e @@ -634,7 +634,7 @@ def _getGDALFormats(): """Get dictionary of available GDAL drivers""" try: ret = grass.read_command("r.in.gdal", quiet=True, flags="f") - except: + except Exception: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) @@ -644,7 +644,7 @@ def _getOGRFormats(): """Get dictionary of available OGR drivers""" try: ret = grass.read_command("v.in.ogr", quiet=True, flags="f") - except: + except Exception: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py index 6ff1345c884..df92b0d4e5f 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -125,7 +125,7 @@ def __processFile(self): try: self.layerManager["pos"] = (posVal[0], posVal[1]) self.layerManager["size"] = (posVal[2], posVal[3]) - except: + except Exception: pass # current working directory cwdPath = self.__getNodeText(node_lm, "cwd") @@ -157,7 +157,7 @@ def __processFile(self): try: pos = (posVal[0], posVal[1]) size = (posVal[2], posVal[3]) - except: + except Exception: pos = None size = None # this happens on Windows when mapwindow is minimized when @@ -2023,7 +2023,7 @@ def _get_value(self, line): """Get value of element""" try: return line.strip(" ").split(" ")[1].strip(" ") - except: + except Exception: return "" def _get_element(self, line): diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index 3db3bf40918..c5a5901a814 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -208,7 +208,7 @@ def LoadData(self, layer, columns=None, where=None, sql=None): try: # for maps connected via v.external keyId = columns.index(keyColumn) - except: + except Exception: keyId = -1 # read data @@ -963,7 +963,7 @@ def OnLayerPageChanged(self, event): self.layerPage[self.selLayer]["data"] ).GetItemCount() ) - except: + except Exception: pass if idCol: @@ -1645,7 +1645,7 @@ def OnDataItemAdd(self, event): if dlg.ShowModal() == wx.ID_OK: try: # get category number cat = int(dlg.GetValues(columns=[keyColumn])[0]) - except: + except Exception: cat = -1 try: @@ -1678,7 +1678,7 @@ def OnDataItemAdd(self, event): values[i] = int(float(values[i])) elif tlist.columns[columnName[i]]["ctype"] == float: values[i] = float(values[i]) - except: + except Exception: raise ValueError( _("Value '%(value)s' needs to be entered as %(type)s.") % { @@ -3818,7 +3818,7 @@ def OnDeleteLayer(self, event): """Delete layer""" try: layer = int(self.deleteLayer.GetValue()) - except: + except Exception: return RunCommand( @@ -3865,10 +3865,10 @@ def OnChangeLayer(self, event): """Layer number of layer to be deleted is changed""" try: layer = int(event.GetString()) - except: + except Exception: try: layer = self.mapDBInfo.layers.keys()[0] - except: + except Exception: return if self.GetCurrentPage() == self.modifyPanel: diff --git a/gui/wxpython/dbmgr/dialogs.py b/gui/wxpython/dbmgr/dialogs.py index 1a3c3af6ee2..845ba6c3fc5 100644 --- a/gui/wxpython/dbmgr/dialogs.py +++ b/gui/wxpython/dbmgr/dialogs.py @@ -225,7 +225,7 @@ def GetSQLString(self, updateValues=False): id = columns[name]["ids"][idx] try: newvalue = self.FindWindowById(id).GetValue() - except: + except Exception: newvalue = self.FindWindowById(id).GetLabel() if newvalue: diff --git a/gui/wxpython/dbmgr/manager.py b/gui/wxpython/dbmgr/manager.py index c866bd55650..9809aeb52ae 100644 --- a/gui/wxpython/dbmgr/manager.py +++ b/gui/wxpython/dbmgr/manager.py @@ -70,7 +70,7 @@ def __init__( self.parent = parent try: mapdisplay = self.parent.GetMapDisplay() - except: + except Exception: mapdisplay = None DbMgrBase.__init__( diff --git a/gui/wxpython/dbmgr/sqlbuilder.py b/gui/wxpython/dbmgr/sqlbuilder.py index eaada441652..ef6119b1e4d 100644 --- a/gui/wxpython/dbmgr/sqlbuilder.py +++ b/gui/wxpython/dbmgr/sqlbuilder.py @@ -360,7 +360,7 @@ def OnUniqueValues(self, event, justsample=False): try: idx = self.list_columns.GetSelections()[0] column = self.list_columns.GetString(idx) - except: + except Exception: self.list_values.Clear() return diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py index 3e948dc3c91..8a87e67168e 100644 --- a/gui/wxpython/gcp/manager.py +++ b/gui/wxpython/gcp/manager.py @@ -896,7 +896,7 @@ def OnSrcSelection(self, event): if p.returncode == 0: print("returncode = ", str(p.returncode)) self.parent.Map.region = self.parent.Map.GetRegion() - except: + except Exception: pass def OnTgtRastSelection(self, event): diff --git a/gui/wxpython/gui_core/dialogs.py b/gui/wxpython/gui_core/dialogs.py index e4c9cd50081..67ec181082a 100644 --- a/gui/wxpython/gui_core/dialogs.py +++ b/gui/wxpython/gui_core/dialogs.py @@ -1217,7 +1217,7 @@ def _filter(self, data): try: if re.compile(self.flt_pattern).search(dt): flt_data.append(dt) - except: + except Exception: pass return flt_data @@ -1662,7 +1662,7 @@ def OnFilter(self, event): try: if re.compile(event.GetString()).search(layer): list.append(layer) - except: + except Exception: pass list = naturally_sorted(list) diff --git a/gui/wxpython/gui_core/forms.py b/gui/wxpython/gui_core/forms.py index 937b31321a9..f56df23b838 100644 --- a/gui/wxpython/gui_core/forms.py +++ b/gui/wxpython/gui_core/forms.py @@ -2019,7 +2019,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar # check wildcard try: fExt = os.path.splitext(p.get("key_desc", ["*.*"])[0])[1] - except: + except Exception: fExt = None if not fExt: fMask = "*" diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index 6c87b444081..1f8e5b39789 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -568,15 +568,15 @@ def _langString(self, k, v): allStr = "%s :" % k.upper() try: allStr += _(" %d translated" % v["good"]) - except: + except Exception: pass try: allStr += _(" %d fuzzy" % v["fuzzy"]) - except: + except Exception: pass try: allStr += _(" %d untranslated" % v["bad"]) - except: + except Exception: pass return allStr @@ -591,7 +591,7 @@ def _langBox(self, par, k, v): ) tgood.SetForegroundColour(wx.Colour(35, 142, 35)) langBox.Add(tgood) - except: + except Exception: tgood = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tgood) try: @@ -600,7 +600,7 @@ def _langBox(self, par, k, v): ) tfuzzy.SetForegroundColour(wx.Colour(255, 142, 0)) langBox.Add(tfuzzy) - except: + except Exception: tfuzzy = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tfuzzy) try: @@ -609,7 +609,7 @@ def _langBox(self, par, k, v): ) tbad.SetForegroundColour(wx.Colour(255, 0, 0)) langBox.Add(tbad) - except: + except Exception: tbad = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tbad) return langBox @@ -846,7 +846,7 @@ def fillContentsFromFile(self, htmlFile, skipDescription=True): contents.append(line) self.SetPage("".join(contents)) self.loaded = True - except: # The Manual file was not found + except Exception: # The Manual file was not found self.loaded = False diff --git a/gui/wxpython/gui_core/gselect.py b/gui/wxpython/gui_core/gselect.py index de9a7d67636..170e162b2fe 100644 --- a/gui/wxpython/gui_core/gselect.py +++ b/gui/wxpython/gui_core/gselect.py @@ -482,7 +482,7 @@ def GetElementList(self, elements=None, exclude=False): try: self.seltree.EnsureVisible(item) self.seltree.SelectItem(item) - except: + except Exception: pass def _getElementList(self, element, mapsets=None, elements=None, exclude=False): diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 7630c6f03ad..098c1b94fb9 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -754,7 +754,7 @@ def _validate(self, win): if text: try: datetime.strptime(text, "%Y-%m-%d") - except: + except Exception: self._notvalid() return False diff --git a/gui/wxpython/image2target/ii2t_gis_set.py b/gui/wxpython/image2target/ii2t_gis_set.py index 12ee5938849..71ee5055cee 100644 --- a/gui/wxpython/image2target/ii2t_gis_set.py +++ b/gui/wxpython/image2target/ii2t_gis_set.py @@ -94,7 +94,7 @@ def __init__(self, parent=None, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE): self.hbitmap = wx.StaticBitmap( self.panel, wx.ID_ANY, wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG) ) - except: + except Exception: self.hbitmap = wx.StaticBitmap( self.panel, wx.ID_ANY, BitmapFromImage(wx.EmptyImage(530, 150)) ) @@ -824,7 +824,7 @@ def DeleteMapset(self, event): shutil.rmtree(os.path.join(self.gisdbase, location, mapset)) self.OnSelectLocation(None) self.lbmapsets.SetSelection(0) - except: + except Exception: wx.MessageBox(message=_("Unable to delete mapset")) dlg.Destroy() @@ -856,7 +856,7 @@ def DeleteLocation(self, event): self.lblocations.SetSelection(0) self.OnSelectLocation(None) self.lbmapsets.SetSelection(0) - except: + except Exception: wx.MessageBox(message=_("Unable to delete location")) dlg.Destroy() @@ -1163,7 +1163,7 @@ def _getDefaultMapsetName(self): defaultName = getpass.getuser() # raise error if not ascii (not valid mapset name) defaultName.encode("ascii") - except: # whatever might go wrong + except Exception: # whatever might go wrong defaultName = "user" return defaultName diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py index 2828a3b0a58..e15cb1dd695 100644 --- a/gui/wxpython/image2target/ii2t_manager.py +++ b/gui/wxpython/image2target/ii2t_manager.py @@ -900,7 +900,7 @@ def OnSrcSelection(self, event): if p.returncode == 0: print("returncode = ", str(p.returncode)) self.parent.Map.region = self.parent.Map.GetRegion() - except: + except Exception: pass def OnTgtRastSelection(self, event): diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index d823dfb6e1a..9866a38e796 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -596,7 +596,7 @@ def _renderscattplts(self, scatt_ids, cats, cats_attrs): try: self.cat_ids.remove(c) scatt_dt[c]["render"] = True - except: + except Exception: scatt_dt[c]["render"] = False if self.scatt_mgr.pol_sel_mode[0]: @@ -673,7 +673,7 @@ def ChangePosition(self, cat_id, new_pos): try: pos = self.cats_ids.index(cat_id) - except: + except Exception: return False if pos > new_pos: diff --git a/gui/wxpython/iscatt/frame.py b/gui/wxpython/iscatt/frame.py index 9ff5a6ceac6..3a4eda67236 100644 --- a/gui/wxpython/iscatt/frame.py +++ b/gui/wxpython/iscatt/frame.py @@ -249,7 +249,7 @@ def CursorPlotMove(self, x, y, scatt_id): x = int(round(x)) y = int(round(y)) coords = True - except: + except Exception: coords = False pane = self._getPane(scatt_id) diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index 819a80ffb95..fc0308fc06b 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -269,7 +269,7 @@ def show_menu_errors(messages): y = client_disp[1] self.SetPosition((x, y)) self.SetSize((w, h)) - except: + except Exception: pass else: # does center (of screen) make sense for lmgr? @@ -883,7 +883,7 @@ def OnCBPageChanged(self, event): try: self.GetMapDisplay().SetFocus() self.GetMapDisplay().Raise() - except: + except Exception: pass event.Skip() @@ -1123,7 +1123,7 @@ def GetMenuCmd(self, event): try: cmdlist = cmd.split(" ") - except: # already list? + except Exception: # already list? cmdlist = cmd # check list of dummy commands for GUI modules that do not have GRASS @@ -1135,7 +1135,7 @@ def GetMenuCmd(self, event): layer = self.GetLayerTree().layer_selected name = self.GetLayerTree().GetLayerInfo(layer, key="maplayer").name type = self.GetLayerTree().GetLayerInfo(layer, key="type") - except: + except Exception: layer = None if layer and len(cmdlist) == 1: # only if no parameters given @@ -1183,7 +1183,7 @@ def OnVDigit(self, event): # available only for vector map layers try: mapLayer = tree.GetLayerInfo(layer, key="maplayer") - except: + except Exception: mapLayer = None if not mapLayer or mapLayer.GetType() != "vector": @@ -1864,7 +1864,7 @@ def OnShowAttributeTable(self, event, selection=None): # available only for vector map layers try: maptype = tree.GetLayerInfo(layer, key="maplayer").type - except: + except Exception: maptype = None if not maptype or maptype != "vector": diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py index 03ae921b2ec..7dafa504bc8 100644 --- a/gui/wxpython/lmgr/layertree.py +++ b/gui/wxpython/lmgr/layertree.py @@ -1746,7 +1746,7 @@ def OnDeleteLayer(self, event): try: item.properties.Close(True) - except: + except Exception: pass if item != self.root: @@ -1762,7 +1762,7 @@ def OnDeleteLayer(self, event): try: if self.GetLayerInfo(item, key="type") != "group": self.Map.DeleteLayer(self.GetLayerInfo(item, key="maplayer")) - except: + except Exception: pass # redraw map if auto-rendering is enabled @@ -2005,7 +2005,7 @@ def OnDrop(self, dropTarget, dragItem): # save everything associated with item to drag try: old = dragItem # make sure this member exists - except: + except Exception: return Debug.msg(4, "LayerTree.OnDrop(): layer=%s" % (self.GetItemText(dragItem))) @@ -2052,7 +2052,7 @@ def RecreateItem(self, dragItem, dropTarget, parent=None): newctrl.SetValue( self.GetLayerInfo(dragItem, key="maplayer").GetCmd(string=True) ) - except: + except Exception: pass newctrl.Bind(wx.EVT_TEXT_ENTER, self.OnCmdChanged) data = self.GetPyData(dragItem) diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py index 4f3a2924847..e8e112a5d40 100644 --- a/gui/wxpython/location_wizard/wizard.py +++ b/gui/wxpython/location_wizard/wizard.py @@ -618,7 +618,7 @@ def OnSearch(self, event): self.proj, self.projdesc = self.projlist.Search( index=[0, 1], pattern=search_str ) - except: + except Exception: self.proj = self.projdesc = "" event.Skip() @@ -1195,15 +1195,15 @@ def OnDText(self, event): self.datumparams = self.parent.datums[self.datum][2] try: self.datumparams.remove("dx=0.0") - except: + except Exception: pass try: self.datumparams.remove("dy=0.0") - except: + except Exception: pass try: self.datumparams.remove("dz=0.0") - except: + except Exception: pass nextButton.Enable(True) @@ -1218,7 +1218,7 @@ def OnDSearch(self, event): self.datum, self.ellipsoid, self.datumdesc = self.datumlist.Search( index=[0, 1, 2], pattern=search_str ) - except: + except Exception: self.datum = self.datumdesc = self.ellipsoid = "" event.Skip() @@ -1399,7 +1399,7 @@ def OnSearch(self, event): self.ellipseparams = self.parent.ellipsoids[self.ellipse][1] else: self.ellipseparams = self.parent.planetary_ellipsoids[self.ellipse][1] - except: + except Exception: self.ellipse = self.ellipsedesc = self.ellipseparams = "" event.Skip() @@ -1945,7 +1945,7 @@ def OnText(self, event): self.epsgcode = event.GetString() try: self.epsgcode = int(self.epsgcode) - except: + except Exception: self.epsgcode = None nextButton = wx.FindWindowById(wx.ID_FORWARD) @@ -2578,7 +2578,7 @@ def __readData(self): plist.append(p) self.projections[proj.lower().strip()] = (projdesc.strip(), plist) self.projdesc[proj.lower().strip()] = projdesc.strip() - except: + except Exception: continue f.close() @@ -2642,7 +2642,7 @@ def __readData(self): try: pparam, datatype, proj4term, desc = line.split(":") self.paramdesc[pparam] = (datatype, proj4term, desc) - except: + except Exception: continue f.close() diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 9a26378eb1e..59ad1982e06 100644 --- a/gui/wxpython/mapdisp/main.py +++ b/gui/wxpython/mapdisp/main.py @@ -176,7 +176,7 @@ def GetLayersFromCmdFile(self): mapFile = line.split("=", 1)[1].strip() try: k, v = line[2:].strip().split("=", 1) - except: + except Exception: pass render_env[k] = v continue diff --git a/gui/wxpython/mapwin/base.py b/gui/wxpython/mapwin/base.py index 3a27713dfd9..9c8accc8f99 100644 --- a/gui/wxpython/mapwin/base.py +++ b/gui/wxpython/mapwin/base.py @@ -220,7 +220,7 @@ def HandlersCaller(self, event, handlers): for handler in handlers: try: handler(event) - except: + except Exception: handlers.remove(handler) GError( parent=self, @@ -309,7 +309,7 @@ def UnregisterAllHandlers(self): try: handler("unregistered") handlers.remove(handler) - except: + except Exception: GError( parent=self, message=_( @@ -348,7 +348,7 @@ def UnregisterMouseEventHandler(self, event, handler): grass.warning( _("Handler: %s was not registered") % handler.__name__ ) - except: + except Exception: GError( parent=self, message=_( diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py index 23989ae865f..967e927e423 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -1029,7 +1029,7 @@ def _updateMFinished(self, renderVector=True): for item in self.graphicsSetList: try: item.Draw() - except: + except Exception: GError( parent=self, message=_( @@ -1169,7 +1169,7 @@ def MouseDraw(self, pdc=None, begin=None, end=None): r.Inflate(4, 4) try: pdc.ClearId(boxid) - except: + except Exception: pass self.RefreshRect(r, False) pdc.SetId(boxid) @@ -1186,7 +1186,7 @@ def MouseDraw(self, pdc=None, begin=None, end=None): r.Inflate(4, 4) try: pdc.ClearId(self.lineid) - except: + except Exception: pass self.RefreshRect(r, False) pdc.SetId(self.lineid) @@ -1734,13 +1734,13 @@ def ClearLines(self, pdc=None): try: pdc.ClearId(self.lineid) pdc.RemoveId(self.lineid) - except: + except Exception: pass try: pdc.ClearId(self.plineid) pdc.RemoveId(self.plineid) - except: + except Exception: pass Debug.msg( @@ -1762,7 +1762,7 @@ def Pixel2Cell(self, xyCoords): try: x = int(xyCoords[0]) y = int(xyCoords[1]) - except: + except Exception: return None if self.Map.region["ewres"] > self.Map.region["nsres"]: @@ -1783,7 +1783,7 @@ def Cell2Pixel(self, enCoords): try: east = float(enCoords[0]) north = float(enCoords[1]) - except: + except Exception: return None if self.Map.region["ewres"] > self.Map.region["nsres"]: diff --git a/gui/wxpython/mapwin/graphics.py b/gui/wxpython/mapwin/graphics.py index 0bc94bae6d2..58a04b4848e 100644 --- a/gui/wxpython/mapwin/graphics.py +++ b/gui/wxpython/mapwin/graphics.py @@ -388,7 +388,7 @@ def _clearId(self, drawid): """Clears old object before drawing new object.""" try: self.pdc.ClearId(drawid) - except: + except Exception: pass diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py index 626c0ea93d5..8c9c3e8ab2b 100644 --- a/gui/wxpython/modules/colorrules.py +++ b/gui/wxpython/modules/colorrules.py @@ -321,7 +321,7 @@ def LoadRules(self): else: value = float(self.ruleslines[item][self.attributeType]) self.mainPanel.FindWindowById(item + 2000).SetValue(value) - except: + except Exception: continue if message: @@ -403,7 +403,7 @@ def _initLayer(self): layer = sel else: layer = self.layerTree.FindItemByData(key="type", value=self.mapType) - except: + except Exception: layer = None if layer: mapLayer = self.layerTree.GetLayerInfo(layer, key="maplayer") diff --git a/gui/wxpython/modules/histogram.py b/gui/wxpython/modules/histogram.py index 23fd8ab97b2..85e9b4e8c1a 100644 --- a/gui/wxpython/modules/histogram.py +++ b/gui/wxpython/modules/histogram.py @@ -258,7 +258,7 @@ def UpdateHistDone(self): return try: id = self.imagedict[self.img] - except: + except Exception: return # paint images to PseudoDC @@ -525,7 +525,7 @@ def OnCloseWindow(self, event): """ try: self.propwin.Close(True) - except: + except Exception: pass self.Map.Clean() self.Destroy() diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py index df1882c6ed6..16e9b96f0e4 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -497,7 +497,7 @@ def OnRun(self, event): if nBandsStr: try: nBands = int(nBandsStr.rstrip("\n")) - except: + except Exception: pass if nBands < 0: GWarning(_("Unable to determine number of raster bands"), parent=self) diff --git a/gui/wxpython/modules/mcalc_builder.py b/gui/wxpython/modules/mcalc_builder.py index 47c317fb937..84319810a73 100644 --- a/gui/wxpython/modules/mcalc_builder.py +++ b/gui/wxpython/modules/mcalc_builder.py @@ -608,7 +608,7 @@ def _addSomething(self, what): if newmcalcstr[-1] != " ": newmcalcstr += " " position_offset += 1 - except: + except Exception: pass newmcalcstr += what @@ -617,7 +617,7 @@ def _addSomething(self, what): try: if newmcalcstr[-1] != " " and mcalcstr[position] != " ": newmcalcstr += " " - except: + except Exception: newmcalcstr += " " newmcalcstr += mcalcstr[position:] @@ -632,7 +632,7 @@ def _addSomething(self, what): try: if newmcalcstr[position + position_offset] == " ": position_offset += 1 - except: + except Exception: pass self.text_mcalc.SetInsertionPoint(position + position_offset) diff --git a/gui/wxpython/nviz/mapwindow.py b/gui/wxpython/nviz/mapwindow.py index 52548983f58..faf1b6730cf 100644 --- a/gui/wxpython/nviz/mapwindow.py +++ b/gui/wxpython/nviz/mapwindow.py @@ -1389,7 +1389,7 @@ def LoadDataLayers(self): GError(parent=self, message=e.value) # when nviz.tools is not yet ready # during opening 3D view 2nd time - except: + except Exception: pass stop = grass.clock() diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index 686be2e98ef..20df3f75f96 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -158,7 +158,7 @@ def SetInitialMaps(self): else: try: selection = layers[0].GetName() - except: + except Exception: continue if ltype == "raster": self.FindWindowById(self.win["surface"]["map"]).SetValue(selection) @@ -740,14 +740,14 @@ def _createDataPage(self): style=fpb.FPB_DEFAULT_STYLE, extraStyle=fpb.FPB_SINGLE_FOLD, ) - except: + except Exception: try: # wxpython >= 2.8.11 self.foldpanelData = fpb.FoldPanelBar( parent=self.mainPanelData, id=wx.ID_ANY, agwStyle=fpb.FPB_SINGLE_FOLD, ) - except: # to be sure + except Exception: # to be sure self.foldpanelData = fpb.FoldPanelBar( parent=self.mainPanelData, id=wx.ID_ANY, style=fpb.FPB_SINGLE_FOLD ) @@ -820,14 +820,14 @@ def _createAppearancePage(self): style=fpb.FPB_DEFAULT_STYLE, extraStyle=fpb.FPB_SINGLE_FOLD, ) - except: + except Exception: try: # wxpython >= 2.8.11 self.foldpanelAppear = fpb.FoldPanelBar( parent=self.mainPanelAppear, id=wx.ID_ANY, agwStyle=fpb.FPB_SINGLE_FOLD, ) - except: # to be sure + except Exception: # to be sure self.foldpanelAppear = fpb.FoldPanelBar( parent=self.mainPanelAppear, id=wx.ID_ANY, style=fpb.FPB_SINGLE_FOLD ) @@ -3416,7 +3416,7 @@ def OnSetSurface(self, event): name = event.GetString() try: data = self._getLayerPropertiesByName(name, mapType="raster")["surface"] - except: + except Exception: self.EnablePage("fringe", False) return @@ -3441,7 +3441,7 @@ def OnSetVector(self, event): name = event.GetString() try: data = self._getLayerPropertiesByName(name, mapType="vector")["vector"] - except: + except Exception: self.EnablePage("vector", False) return layer = self._getMapLayerByName(name, mapType="vector") @@ -3453,7 +3453,7 @@ def OnSetRaster3D(self, event): name = event.GetString() try: data = self._getLayerPropertiesByName(name, mapType="raster_3d")["volume"] - except: + except Exception: self.EnablePage("volume", False) return @@ -5048,7 +5048,7 @@ def OnCPlaneSelection(self, event): try: planeIndex = int(plane.split()[-1]) - 1 self.EnablePage("cplane", enabled=True) - except: + except Exception: planeIndex = -1 self.EnablePage("cplane", enabled=False) self.mapWindow.SelectCPlane(planeIndex) @@ -5066,7 +5066,7 @@ def OnCPlaneChanging(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except: # TODO disabled page + except Exception: # TODO disabled page planeIndex = -1 if event.GetId() in ( @@ -5110,7 +5110,7 @@ def OnCPlaneShading(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except: # TODO disabled page + except Exception: # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex]["shading"] = shading @@ -5125,7 +5125,7 @@ def OnCPlaneReset(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except: # TODO disabled page + except Exception: # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex] = copy.deepcopy( diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py index fc89994607a..21d536fd681 100644 --- a/gui/wxpython/photo2image/ip2i_manager.py +++ b/gui/wxpython/photo2image/ip2i_manager.py @@ -167,7 +167,7 @@ def __init__( if p.returncode == 0: print("returncode = ", str(p.returncode)) self.Map.region = self.Map.GetRegion() - except: + except Exception: pass self.SwitchEnv("source") diff --git a/gui/wxpython/psmap/frame.py b/gui/wxpython/psmap/frame.py index ef6bc17f59b..560a3832535 100644 --- a/gui/wxpython/psmap/frame.py +++ b/gui/wxpython/psmap/frame.py @@ -1038,7 +1038,7 @@ def makePSFont(self, textDict): fn = wx.Font( pointSize=fontsize, family=family, style=style, weight=weight, face=face ) - except: + except Exception: fn = wx.Font( pointSize=fontsize, family=wx.FONTFAMILY_DEFAULT, @@ -1060,7 +1060,7 @@ def getTextExtent(self, textDict): dc.SetFont(fn) w, h, lh = dc.GetFullMultiLineTextExtent(textDict["text"]) return (w, h) - except: + except Exception: return (0, 0) def getInitMap(self): diff --git a/gui/wxpython/rlisetup/wizard.py b/gui/wxpython/rlisetup/wizard.py index 320eb370a04..f371e7c7eb8 100644 --- a/gui/wxpython/rlisetup/wizard.py +++ b/gui/wxpython/rlisetup/wizard.py @@ -688,7 +688,7 @@ def OnVector(self, event): def OnLayer(self, event): try: self.vectorlayer = self.vectlayer.GetValue() - except: + except Exception: self.vectorlayer = None next = wx.FindWindowById(wx.ID_FORWARD) next.Enable(self.CheckInput()) diff --git a/gui/wxpython/startup/locdownload.py b/gui/wxpython/startup/locdownload.py index 588d30960d0..d676038a74e 100644 --- a/gui/wxpython/startup/locdownload.py +++ b/gui/wxpython/startup/locdownload.py @@ -93,7 +93,7 @@ def write(self, string): heigth = self._get_heigth(string) wx.CallAfter(self.out.SetLabel, string) self._resize(heigth) - except: + except Exception: # window closed -> PyDeadObjectError pass diff --git a/gui/wxpython/tplot/frame.py b/gui/wxpython/tplot/frame.py index 0b36b3704fb..de4eea8dadf 100755 --- a/gui/wxpython/tplot/frame.py +++ b/gui/wxpython/tplot/frame.py @@ -210,7 +210,7 @@ def _layout(self): self.coorval = gselect.CoordinatesSelect( parent=self.controlPanelRaster, giface=self._giface ) - except: + except Exception: self.coorval = TextCtrl( parent=self.controlPanelRaster, id=wx.ID_ANY, @@ -279,7 +279,7 @@ def _layout(self): self.cats = gselect.VectorCategorySelect( parent=self.controlPanelVector, giface=self._giface ) - except: + except Exception: self.cats = TextCtrl( parent=self.controlPanelVector, id=wx.ID_ANY, @@ -1032,10 +1032,10 @@ def OnRedraw(self, event=None): try: getcoors = self.coorval.coordsField.GetValue() - except: + except Exception: try: getcoors = self.coorval.GetValue() - except: + except Exception: getcoors = None if getcoors and getcoors != "": try: @@ -1264,7 +1264,7 @@ def SetDatasets( return try: self.coorval.coordsField.SetValue(",".join(coors)) - except: + except Exception: self.coorval.SetValue(",".join(coors)) if self.datasetsV: vdatas = ",".join(map(lambda x: x[0] + "@" + x[1], self.datasetsV)) @@ -1466,7 +1466,7 @@ def __call__(self, event): for a in event.artist.get_xdata(): try: d = self.convert(a) - except: + except Exception: d = a xData.append(d) x = xData[np.argmin(abs(xData - x))] diff --git a/gui/wxpython/vdigit/dialogs.py b/gui/wxpython/vdigit/dialogs.py index 395f92a4102..93c2617dc60 100644 --- a/gui/wxpython/vdigit/dialogs.py +++ b/gui/wxpython/vdigit/dialogs.py @@ -256,7 +256,7 @@ def OnEndEdit(self, event): self.cats[self.fid][layerNew] = [] self.cats[self.fid][layerNew].append(catNew) self.cats[self.fid][layerOld].remove(catOld) - except: + except Exception: event.Veto() self.list.SetItem(itemIndex, 0, str(layerNew)) self.list.SetItem(itemIndex, 1, str(catNew)) diff --git a/gui/wxpython/vdigit/mapwindow.py b/gui/wxpython/vdigit/mapwindow.py index 650fe65261a..af14ea41b0a 100644 --- a/gui/wxpython/vdigit/mapwindow.py +++ b/gui/wxpython/vdigit/mapwindow.py @@ -290,7 +290,7 @@ def OnLeftDownAddLine(self, event): """Left mouse button pressed - add new feature""" try: mapLayer = self.toolbar.GetLayer().GetName() - except: + except Exception: return if self.toolbar.GetAction("type") in ["point", "centroid"]: @@ -482,7 +482,7 @@ def OnLeftDownDisplayCA(self, event): """ try: mapLayer = self.toolbar.GetLayer().GetName() - except: + except Exception: return coords = self.Pixel2Cell(self.mouse["begin"]) @@ -625,7 +625,7 @@ def OnLeftDownUndo(self, event): ], ) # self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1]) - except: + except Exception: pass if action == "editLine": @@ -691,7 +691,7 @@ def _onLeftDown(self, event): """Left mouse button donw - vector digitizer various actions""" try: mapLayer = self.toolbar.GetLayer().GetName() - except: + except Exception: GMessage(parent=self, message=_("No vector map selected for editing.")) event.Skip() return @@ -1102,7 +1102,7 @@ def _onRightUp(self, event): # -> add new line / boundary try: mapName = self.toolbar.GetLayer().GetName() - except: + except Exception: mapName = None GError(parent=self, message=_("No vector map selected for editing.")) diff --git a/gui/wxpython/vdigit/preferences.py b/gui/wxpython/vdigit/preferences.py index cdd88f6b6d5..4649bbb1820 100644 --- a/gui/wxpython/vdigit/preferences.py +++ b/gui/wxpython/vdigit/preferences.py @@ -199,7 +199,7 @@ def _createGeneralPage(self, notebook): self.snappingUnit.SetSelection( UserSettings.Get(group="vdigit", key="snapping", subkey="unit") ) - except: + except Exception: self.snappingUnit.SetSelection(0) self.snappingUnit.Bind(wx.EVT_CHOICE, self.OnChangeSnappingUnits) flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL) diff --git a/gui/wxpython/wxplot/base.py b/gui/wxpython/wxplot/base.py index 3ae016db748..791e75c6573 100755 --- a/gui/wxpython/wxplot/base.py +++ b/gui/wxpython/wxplot/base.py @@ -204,7 +204,7 @@ def InitRasterOpts(self, rasterList, plottype): try: ret = grass.raster_info(r) - except: + except Exception: continue # if r.info cannot parse map, skip it @@ -270,7 +270,7 @@ def InitRasterPairs(self, rasterList, plottype): ret0 = grass.raster_info(rpair[0]) ret1 = grass.raster_info(rpair[1]) - except: + except Exception: continue # if r.info cannot parse map, skip it diff --git a/gui/wxpython/wxplot/histogram.py b/gui/wxpython/wxplot/histogram.py index b895ba19683..8f01500e9ca 100644 --- a/gui/wxpython/wxplot/histogram.py +++ b/gui/wxpython/wxplot/histogram.py @@ -99,7 +99,7 @@ def OnCreateHist(self, event): """ try: self.SetCursor(StockCursor(wx.CURSOR_ARROW)) - except: + except Exception: pass self.SetGraphStyle() diff --git a/gui/wxpython/wxplot/profile.py b/gui/wxpython/wxplot/profile.py index 1b55da68919..c1ae12010fa 100644 --- a/gui/wxpython/wxplot/profile.py +++ b/gui/wxpython/wxplot/profile.py @@ -248,7 +248,7 @@ def SetupProfile(self): # delete extra first segment point try: self.seglist.pop(0) - except: + except Exception: pass # @@ -489,7 +489,7 @@ def OnStats(self, event): statstr += "median: %f\n" % numpy.median(a) statstr += "distance along transect: %f\n\n" % self.transect_length message.append(statstr) - except: + except Exception: pass stats = PlotStatsFrame(self, id=wx.ID_ANY, message=message, title=title) diff --git a/lib/init/grass.py b/lib/init/grass.py index 6d9d8b3b3e1..5fdec3b7a2d 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -543,7 +543,7 @@ def create_gisrc(tmpdir, gisrcrc): if "UNKNOWN" in s: try_remove(gisrcrc) s = None - except: + except Exception: s = None # Copy the global grassrc file to the session grassrc file @@ -742,7 +742,7 @@ def set_paths(grass_config_dir): s = p.stdout.read() p.wait() sys_man_path = s.strip() - except: + except Exception: pass if sys_man_path: @@ -1847,7 +1847,7 @@ def say_hello(): revision = linerev.split(" ")[1] sys.stderr.write(" (" + revision + ")") - except: + except Exception: pass @@ -2213,7 +2213,7 @@ def print_params(params): try: revision = linerev.split(" ")[1] sys.stdout.write("%s\n" % revision[1:]) - except: + except Exception: sys.stdout.write("No SVN revision defined\n") elif arg == "version": sys.stdout.write("%s\n" % GRASS_VERSION) @@ -2251,7 +2251,7 @@ def get_username(): user = s.strip() if type(user) is bytes: user = decode(user) - except: + except Exception: pass if not user: user = "user_%d" % os.getuid() diff --git a/locale/grass_po_stats.py b/locale/grass_po_stats.py index 81ccbab167d..6a839cbafb2 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -144,7 +144,7 @@ def writejson(stats, outfile): fout.close() try: os.remove("messages.mo") - except: + except Exception: pass diff --git a/man/build_keywords.py b/man/build_keywords.py index 5b2b41359b1..02710982410 100644 --- a/man/build_keywords.py +++ b/man/build_keywords.py @@ -81,17 +81,17 @@ def get_module_man_html_file_path(module): try: index_keys = lines.index("

KEYWORDS

\n") + 1 index_desc = lines.index("

NAME

\n") + 1 - except: + except Exception: continue try: keys = lines[index_keys].split(",") - except: + except Exception: continue for key in keys: key = key.strip() try: key = key.split(">")[1].split("<")[0] - except: + except Exception: pass if not key: exit("Empty keyword from file %s line: %s" % (fname, lines[index_keys])) @@ -104,10 +104,10 @@ def get_module_man_html_file_path(module): for black in blacklist: try: del keywords[black] - except: + except Exception: try: del keywords[black.lower()] - except: + except Exception: continue for key in sorted(keywords.keys()): diff --git a/man/build_topics.py b/man/build_topics.py index c1a4b3654c7..3068461c4f0 100644 --- a/man/build_topics.py +++ b/man/build_topics.py @@ -24,16 +24,16 @@ try: index_keys = lines.index("

KEYWORDS

\n") + 1 index_desc = lines.index("

NAME

\n") + 1 - except: + except Exception: continue try: key = lines[index_keys].split(",")[1].strip().replace(" ", "_") key = key.split(">")[1].split("<")[0] - except: + except Exception: continue try: desc = lines[index_desc].split("-", 1)[1].strip() - except: + except Exception: desc.strip() if key not in keywords.keys(): keywords[key] = {} diff --git a/python/grass/temporal/abstract_space_time_dataset.py b/python/grass/temporal/abstract_space_time_dataset.py index f3b591977af..edadb346275 100644 --- a/python/grass/temporal/abstract_space_time_dataset.py +++ b/python/grass/temporal/abstract_space_time_dataset.py @@ -1865,7 +1865,7 @@ def get_registered_maps( try: dbif.execute(sql, mapset=self.base.mapset) rows = dbif.fetchall(mapset=self.base.mapset) - except: + except Exception: if connection_state_changed: dbif.close() self.msgr.error( @@ -2427,7 +2427,7 @@ def is_map_registered(self, map_id, dbif=None): try: dbif.execute(sql, (map_id,), mapset=self.base.mapset) row = dbif.fetchone(mapset=self.base.mapset) - except: + except Exception: self.msgr.warning(_("Error in register table request")) raise diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index ab564df2312..07822e5ce4b 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -79,7 +79,7 @@ def _read_map_full_info(lock, conn, data): info = _read_raster_full_info(name, mapset) elif maptype == RPCDefs.TYPE_VECTOR: info = _read_vector_full_info(name, mapset) - except: + except Exception: raise finally: conn.send(info) @@ -294,7 +294,7 @@ def _get_database_name(lock, conn, data): dbstring = dbstring.replace(encode("$GISDBASE"), libgis.G_gisdbase()) dbstring = dbstring.replace(encode("$LOCATION_NAME"), libgis.G_location()) dbstring = dbstring.replace(encode("$MAPSET"), mapset) - except: + except Exception: raise finally: conn.send(decode(dbstring)) @@ -352,7 +352,7 @@ def _available_mapsets(lock, conn, data): mapset_list.reverse() mapset_list.append(current_mapset) mapset_list.reverse() - except: + except Exception: raise finally: conn.send(mapset_list) @@ -386,7 +386,7 @@ def _has_timestamp(lock, conn, data): elif maptype == RPCDefs.TYPE_RASTER3D: if libgis.G_has_raster3d_timestamp(name, mapset) == 1: check = True - except: + except Exception: raise finally: conn.send(check) @@ -436,7 +436,7 @@ def _read_timestamp(lock, conn, data): check = libgis.G_read_raster3d_timestamp(name, mapset, byref(ts)) dates = _convert_timestamp_from_grass(ts) - except: + except Exception: raise finally: conn.send((check, dates)) @@ -480,7 +480,7 @@ def _write_timestamp(lock, conn, data): check = libgis.G_write_vector_timestamp(name, layer, byref(ts)) elif maptype == RPCDefs.TYPE_RASTER3D: check = libgis.G_write_raster3d_timestamp(name, byref(ts)) - except: + except Exception: raise finally: conn.send(check) @@ -517,7 +517,7 @@ def _remove_timestamp(lock, conn, data): check = libgis.G_remove_vector_timestamp(name, layer, mapset) elif maptype == RPCDefs.TYPE_RASTER3D: check = libgis.G_remove_raster3d_timestamp(name, mapset) - except: + except Exception: raise finally: conn.send(check) @@ -557,7 +557,7 @@ def _read_semantic_label(lock, conn, data): "Unable to read semantic label. " "Unsupported map type %s" % maptype ) return -1 - except: + except Exception: raise finally: conn.send(semantic_label) @@ -594,7 +594,7 @@ def _write_semantic_label(lock, conn, data): "Unable to write semantic label. " "Unsupported map type %s" % maptype ) return -2 - except: + except Exception: raise finally: conn.send(True) @@ -628,7 +628,7 @@ def _remove_semantic_label(lock, conn, data): "Unable to remove semantic label. " "Unsupported map type %s" % maptype ) return -2 - except: + except Exception: raise finally: conn.send(check) @@ -662,7 +662,7 @@ def _map_exists(lock, conn, data): if mapset: check = True - except: + except Exception: raise finally: conn.send(check) @@ -690,7 +690,7 @@ def _read_map_info(lock, conn, data): kvp = _read_vector_info(name, mapset) elif maptype == RPCDefs.TYPE_RASTER3D: kvp = _read_raster3d_info(name, mapset) - except: + except Exception: raise finally: conn.send(kvp) @@ -1000,7 +1000,7 @@ def _read_map_history(lock, conn, data): kvp = _read_vector_history(name, mapset) elif maptype == RPCDefs.TYPE_RASTER3D: kvp = _read_raster3d_history(name, mapset) - except: + except Exception: raise finally: conn.send(kvp) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index 68db2716ae5..51adf26170e 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -48,7 +48,7 @@ try: import psycopg2 import psycopg2.extras -except: +except Exception: pass import atexit @@ -410,7 +410,7 @@ def get_tgis_metadata(dbif=None): statement = "SELECT * FROM tgis_metadata;\n" dbif.execute(statement) rows = dbif.fetchall() - except: + except Exception: rows = None if connection_state_changed: @@ -1538,7 +1538,7 @@ def execute(self, statement, args=None): self.cursor.execute(statement, args) else: self.cursor.execute(statement) - except: + except Exception: if connected: self.close() self.msgr.error(_("Unable to execute :\n %(sql)s" % {"sql": statement})) @@ -1581,7 +1581,7 @@ def execute_transaction(self, statement, mapset=None): else: self.cursor.execute(statement) self.connection.commit() - except: + except Exception: if connected: self.close() self.msgr.error( diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py index 29bcc8907de..ad801666122 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -17,7 +17,7 @@ import dateutil.parser as parser has_dateutil = True -except: +except Exception: has_dateutil = False @@ -324,7 +324,7 @@ def modify_datetime( try: dt1 = dt1.replace(year=year + years_to_add, month=residual_months) - except: + except Exception: raise tdelta_months = dt1 - mydate @@ -351,7 +351,7 @@ def modify_datetime( try: dt1 = dt1.replace(year=year - years_to_remove, month=residual_months) - except: + except Exception: raise tdelta_months = dt1 - mydate @@ -832,7 +832,7 @@ def check_datetime_string(time_string, use_dateutil=True): try: return datetime.strptime(time_string, time_format) - except: + except Exception: return _("Unable to parse time string: %s" % time_string) diff --git a/python/grass/temporal/spatial_topology_dataset_connector.py b/python/grass/temporal/spatial_topology_dataset_connector.py index 93fe3270c43..232373c2180 100644 --- a/python/grass/temporal/spatial_topology_dataset_connector.py +++ b/python/grass/temporal/spatial_topology_dataset_connector.py @@ -118,31 +118,31 @@ def get_number_of_spatial_relations(self): relations = {} try: relations["equivalent"] = len(self._spatial_topology["EQUIVALENT"]) - except: + except Exception: relations["equivalent"] = 0 try: relations["overlap"] = len(self._spatial_topology["OVERLAP"]) - except: + except Exception: relations["overlap"] = 0 try: relations["in"] = len(self._spatial_topology["IN"]) - except: + except Exception: relations["in"] = 0 try: relations["contain"] = len(self._spatial_topology["CONTAIN"]) - except: + except Exception: relations["contain"] = 0 try: relations["meet"] = len(self._spatial_topology["MEET"]) - except: + except Exception: relations["meet"] = 0 try: relations["cover"] = len(self._spatial_topology["COVER"]) - except: + except Exception: relations["cover"] = 0 try: relations["covered"] = len(self._spatial_topology["COVERED"]) - except: + except Exception: relations["covered"] = 0 return relations diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index db35f03f071..f0e1af757ed 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -442,7 +442,7 @@ try: import ply.lex as lex import ply.yacc as yacc -except: +except Exception: pass import os @@ -2886,7 +2886,7 @@ def p_t_var_expr_td_hash(self, t): map_i.condition_value.append(boolname) else: map_i.condition_value = boolname - except: + except Exception: self.msgr.fatal( "Error: the given expression does not contain a correct time " "difference object." diff --git a/python/grass/temporal/temporal_granularity.py b/python/grass/temporal/temporal_granularity.py index 3b1b005d533..9c60902e3f7 100644 --- a/python/grass/temporal/temporal_granularity.py +++ b/python/grass/temporal/temporal_granularity.py @@ -90,19 +90,19 @@ def check_granularity_string(granularity, temporal_type): if temporal_type == "absolute": try: num, unit = granularity.split(" ") - except: + except Exception: return False if unit not in SUPPORTED_GRAN: return False try: integer = int(num) - except: + except Exception: return False elif temporal_type == "relative": try: integer = int(granularity) - except: + except Exception: return False else: return False diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index dfae8f86863..b3a314b4fd6 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -387,7 +387,7 @@ def sub_cmdstring(map_i): else: try: map_sub = map_i.get_id() - except: + except Exception: map_sub = map_i return map_sub diff --git a/python/grass/temporal/temporal_topology_dataset_connector.py b/python/grass/temporal/temporal_topology_dataset_connector.py index fddf478ad71..b905ce25855 100644 --- a/python/grass/temporal/temporal_topology_dataset_connector.py +++ b/python/grass/temporal/temporal_topology_dataset_connector.py @@ -160,47 +160,47 @@ def get_number_of_temporal_relations(self): relations = {} try: relations["equal"] = len(self._temporal_topology["EQUAL"]) - except: + except Exception: relations["equal"] = 0 try: relations["follows"] = len(self._temporal_topology["FOLLOWS"]) - except: + except Exception: relations["follows"] = 0 try: relations["precedes"] = len(self._temporal_topology["PRECEDES"]) - except: + except Exception: relations["precedes"] = 0 try: relations["overlaps"] = len(self._temporal_topology["OVERLAPS"]) - except: + except Exception: relations["overlaps"] = 0 try: relations["overlapped"] = len(self._temporal_topology["OVERLAPPED"]) - except: + except Exception: relations["overlapped"] = 0 try: relations["during"] = len(self._temporal_topology["DURING"]) - except: + except Exception: relations["during"] = 0 try: relations["contains"] = len(self._temporal_topology["CONTAINS"]) - except: + except Exception: relations["contains"] = 0 try: relations["starts"] = len(self._temporal_topology["STARTS"]) - except: + except Exception: relations["starts"] = 0 try: relations["started"] = len(self._temporal_topology["STARTED"]) - except: + except Exception: relations["started"] = 0 try: relations["finishes"] = len(self._temporal_topology["FINISHES"]) - except: + except Exception: relations["finishes"] = 0 try: relations["finished"] = len(self._temporal_topology["FINISHED"]) - except: + except Exception: relations["finished"] = 0 return relations diff --git a/scripts/d.frame/d.frame.py b/scripts/d.frame/d.frame.py index 2d75457bee0..7471a986df1 100755 --- a/scripts/d.frame/d.frame.py +++ b/scripts/d.frame/d.frame.py @@ -206,7 +206,7 @@ def calculate_frame(frame, at, width, height): """ try: b, t, l, r = list(map(float, at.split(","))) - except: + except Exception: fatal(_("Invalid frame position: %s") % at) top = round(height - (t / 100.0 * height)) @@ -238,7 +238,7 @@ def create_frame(monitor, frame, at, overwrite=False): width = int(line.split("=", 1)[1].rsplit(" ", 1)[0]) elif "HEIGHT" in line: height = int(line.split("=", 1)[1].rsplit(" ", 1)[0]) - except: + except Exception: pass if width < 0 or height < 0: diff --git a/scripts/d.rast.edit/d.rast.edit.py b/scripts/d.rast.edit/d.rast.edit.py index 4824a17a81c..245b9854eff 100755 --- a/scripts/d.rast.edit/d.rast.edit.py +++ b/scripts/d.rast.edit/d.rast.edit.py @@ -670,7 +670,7 @@ def get_color(self, val): if val not in self.colors: try: self.force_color(val) - except: + except Exception: self.colors[val] = "#ffffff" return self.colors[val] diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index d0b06e53727..368f6ce6078 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -458,7 +458,7 @@ def main(): grass.run_command( "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True ) - except: + except Exception: pass @@ -523,7 +523,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): pb.wait(), pg.wait(), pr.wait() try: pb.terminate(), pg.terminate(), pr.terminate() - except: + except Exception: pass # Cleanup @@ -535,7 +535,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): type="raster", name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), ) - except: + except Exception: pass @@ -577,7 +577,7 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): grass.run_command( "g.remove", flags="f", quiet=True, type="raster", name=panmatch ) - except: + except Exception: pass @@ -703,7 +703,7 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): pb.wait(), pg.wait(), pr.wait() try: pb.terminate(), pg.terminate(), pr.terminate() - except: + except Exception: pass # Cleanup diff --git a/scripts/r.fillnulls/r.fillnulls.py b/scripts/r.fillnulls/r.fillnulls.py index 7744d01ca25..546eee4a1bc 100755 --- a/scripts/r.fillnulls/r.fillnulls.py +++ b/scripts/r.fillnulls/r.fillnulls.py @@ -273,7 +273,7 @@ def main(): type="area", quiet=quiet, ) - except: + except Exception: grass.fatal( _( "abandoned. Removing temporary maps, restoring " @@ -481,7 +481,7 @@ def main(): tmp_rmaps.remove(holename + "_edges") tmp_rmaps.remove(holename + "_dem") tmp_vmaps.remove(holename) - except: + except Exception: pass grass.warning( _( @@ -545,7 +545,7 @@ def main(): tmp_rmaps.remove(holename + "_grown") tmp_rmaps.remove(holename + "_edges") tmp_rmaps.remove(holename + "_dem") - except: + except Exception: pass try: grass.run_command( @@ -569,7 +569,7 @@ def main(): ) try: tmp_vmaps.remove(holename) - except: + except Exception: pass try: grass.run_command( diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py index 3aa4db4f6be..95aa758e501 100755 --- a/scripts/r.in.srtm/r.in.srtm.py +++ b/scripts/r.in.srtm/r.in.srtm.py @@ -230,7 +230,7 @@ def main(): try: zf = zfile.ZipFile(zipfile) zf.extractall() - except: + except Exception: grass.fatal(_("Unable to unzip file.")) grass.message(_("Converting input file to BIL...")) @@ -277,7 +277,7 @@ def main(): try: grass.run_command("r.in.gdal", input=bilfile, out=tileout) - except: + except Exception: grass.fatal(_("Unable to import data")) # nice color table diff --git a/scripts/r.in.wms/srs.py b/scripts/r.in.wms/srs.py index 460e3c14fc1..c581bc09637 100644 --- a/scripts/r.in.wms/srs.py +++ b/scripts/r.in.wms/srs.py @@ -79,7 +79,7 @@ def __init__(self, srs): # code is always the last value try: self.code = int(values[-1]) - except: + except Exception: self.code = values[-1] elif len(values) == 2: # it's an authority:code code diff --git a/scripts/r.in.wms/wms_drv.py b/scripts/r.in.wms/wms_drv.py index 51c9f2037c4..fa789003053 100644 --- a/scripts/r.in.wms/wms_drv.py +++ b/scripts/r.in.wms/wms_drv.py @@ -24,7 +24,7 @@ try: from osgeo import gdal -except: +except Exception: grass.fatal( _( "Unable to load GDAL Python bindings (requires package 'python-gdal' " diff --git a/scripts/r.in.wms/wms_gdal_drv.py b/scripts/r.in.wms/wms_gdal_drv.py index 353de1a679c..d6f81bf02ba 100644 --- a/scripts/r.in.wms/wms_gdal_drv.py +++ b/scripts/r.in.wms/wms_gdal_drv.py @@ -17,7 +17,7 @@ try: from osgeo import gdal -except: +except Exception: grass.fatal( _( "Unable to load GDAL Python bindings (requires package 'python-gdal' being " diff --git a/scripts/v.import/v.import.py b/scripts/v.import/v.import.py index 8bb95fa8737..05fd45d6f30 100755 --- a/scripts/v.import/v.import.py +++ b/scripts/v.import/v.import.py @@ -266,7 +266,7 @@ def main(): if OGRdatasource.lower().endswith("gml"): try: from osgeo import gdal - except: + except Exception: grass.fatal( _( "Unable to load GDAL Python bindings (requires package " @@ -343,7 +343,7 @@ def main(): if OGRdatasource.lower().endswith("gml"): try: from osgeo import gdal - except: + except Exception: grass.fatal( _( "Unable to load GDAL Python bindings (requires package " diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index bd350676444..c64774aa47c 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -77,7 +77,7 @@ def main(): tar = tarfile.TarFile.open(name=input_base, mode="r") try: data_name = tar.getnames()[0] - except: + except Exception: grass.fatal(_("Pack file unreadable")) if flags["p"]: diff --git a/scripts/v.what.strds/v.what.strds.py b/scripts/v.what.strds/v.what.strds.py index ab423461a71..c55fe23daa4 100644 --- a/scripts/v.what.strds/v.what.strds.py +++ b/scripts/v.what.strds/v.what.strds.py @@ -227,7 +227,7 @@ def main(): pymap = Vector(output) try: pymap.open("r") - except: + except Exception: dbif.close() grass.fatal(_("Unable to create vector map <%s>" % output)) diff --git a/utils/gitlog2changelog.py b/utils/gitlog2changelog.py index 6e2bb99fd0f..a47e8f063ee 100755 --- a/utils/gitlog2changelog.py +++ b/utils/gitlog2changelog.py @@ -66,7 +66,7 @@ author = authorList[1] author = author[0 : len(author) - 1] authorFound = True - except: + except Exception: print("Could not parse authorList = '%s'" % (line)) # Match the date line @@ -76,7 +76,7 @@ date = dateList[1] date = date[0 : len(date) - 1] dateFound = True - except: + except Exception: print("Could not parse dateList = '%s'" % (line)) # The Fossil-IDs are ignored: elif line.startswith(" Fossil-ID:") or line.startswith(" [[SVN:"): From f66788a33eaf81e5c682c428f9ee69cd8cdf5667 Mon Sep 17 00:00:00 2001 From: mshukun Date: Mon, 3 Jun 2024 15:45:54 -0400 Subject: [PATCH 2/9] Fix some of broat-exception --- gui/wxpython/core/gconsole.py | 3 ++- gui/wxpython/core/render.py | 2 +- gui/wxpython/core/settings.py | 5 +++-- gui/wxpython/core/utils.py | 11 +++++----- gui/wxpython/core/workspace.py | 6 ++--- gui/wxpython/dbmgr/base.py | 7 +++--- gui/wxpython/gui_core/dialogs.py | 4 ++-- gui/wxpython/gui_core/forms.py | 2 +- gui/wxpython/gui_core/ghelp.py | 6 ++--- gui/wxpython/gui_core/widgets.py | 2 +- gui/wxpython/iscatt/controllers.py | 4 ++-- gui/wxpython/iscatt/frame.py | 2 +- gui/wxpython/lmgr/frame.py | 2 +- gui/wxpython/lmgr/layertree.py | 2 +- gui/wxpython/location_wizard/wizard.py | 10 ++++----- gui/wxpython/mapdisp/main.py | 2 +- gui/wxpython/mapwin/buffered.py | 4 ++-- gui/wxpython/modules/histogram.py | 2 +- gui/wxpython/modules/import_export.py | 2 +- gui/wxpython/modules/mcalc_builder.py | 6 ++--- gui/wxpython/nviz/tools.py | 8 +++---- gui/wxpython/vdigit/mapwindow.py | 2 +- gui/wxpython/wxplot/profile.py | 2 +- lib/init/grass.py | 12 +++++----- locale/grass_po_stats.py | 2 +- man/build_keywords.py | 10 ++++----- man/build_topics.py | 6 ++--- python/grass/temporal/core.py | 2 +- python/grass/temporal/datetime_math.py | 8 +++---- .../spatial_topology_dataset_connector.py | 14 ++++++------ python/grass/temporal/temporal_algebra.py | 2 +- python/grass/temporal/temporal_granularity.py | 6 ++--- .../temporal/temporal_raster_base_algebra.py | 2 +- .../temporal_topology_dataset_connector.py | 22 +++++++++---------- scripts/d.frame/d.frame.py | 4 ++-- scripts/i.pansharpen/i.pansharpen.py | 6 ++--- scripts/r.fillnulls/r.fillnulls.py | 8 +++---- scripts/r.in.srtm/r.in.srtm.py | 7 ++---- scripts/r.in.wms/srs.py | 2 +- scripts/r.in.wms/wms_drv.py | 2 +- scripts/r.in.wms/wms_gdal_drv.py | 2 +- scripts/v.import/v.import.py | 4 ++-- scripts/v.unpack/v.unpack.py | 2 +- scripts/v.what.strds/v.what.strds.py | 2 +- utils/gitlog2changelog.py | 4 ++-- 45 files changed, 113 insertions(+), 112 deletions(-) diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index ac7e07e57d5..a6d6a6e5182 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -37,6 +37,7 @@ import grass.script as grass from grass.script import task as gtask +from grass.exceptions import ScriptError from grass.pydispatch.signal import Signal @@ -676,7 +677,7 @@ def RunCmd( if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) - except Exception: + except ScriptError: task = None else: task = None diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index cd48ac24862..eefc5dd5c5d 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -1242,7 +1242,7 @@ def SetRegion(self, windres=False, windres3=False): return grass_region - except Exception: + except (KeyError, TypeError): return None def GetListOfLayers( diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index b570bb810f7..f01c371adfb 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -110,7 +110,8 @@ def _generateLocale(self): self.locs.sort() # Add a default choice to not override system locale self.locs.insert(0, "system") - except Exception: + except (KeyError, FileNotFoundError, PermissionError, NotADirectoryError, + OSError): # No NLS self.locs = ["system"] @@ -992,7 +993,7 @@ def SaveToFile(self, settings=None): if not os.path.exists(dirPath): try: os.mkdir(dirPath) - except Exception: + except OSError: GError(_("Unable to create settings directory")) return try: diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index 1993193f5da..712a43aa530 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -23,6 +23,7 @@ from grass.script import core as grass from grass.script import task as gtask +from grass.exceptions import CalledModuleError from core.gcmd import RunCommand from core.debug import Debug @@ -76,7 +77,7 @@ def GetTempfile(pref=None): return os.path.join(pref, file) else: return tempfile - except Exception: + except TypeError: return None @@ -254,7 +255,7 @@ def ListOfCatsToRange(cats): try: cats = list(map(int, cats)) - except Exception: + except (TypeError, ValueError): return catstr i = 0 @@ -579,7 +580,7 @@ def GetListOfLocations(dbase): os.path.join(location, "*") ): listOfLocations.append(os.path.basename(location)) - except Exception: + except (TypeError, FileNotFoundError, PermissionError, NotADirectoryError): pass except (UnicodeEncodeError, UnicodeDecodeError) as e: raise e @@ -634,7 +635,7 @@ def _getGDALFormats(): """Get dictionary of available GDAL drivers""" try: ret = grass.read_command("r.in.gdal", quiet=True, flags="f") - except Exception: + except CalledModuleError: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) @@ -644,7 +645,7 @@ def _getOGRFormats(): """Get dictionary of available OGR drivers""" try: ret = grass.read_command("v.in.ogr", quiet=True, flags="f") - except Exception: + except CalledModuleError: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py index df92b0d4e5f..9d412e1041a 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -125,7 +125,7 @@ def __processFile(self): try: self.layerManager["pos"] = (posVal[0], posVal[1]) self.layerManager["size"] = (posVal[2], posVal[3]) - except Exception: + except IndexError: pass # current working directory cwdPath = self.__getNodeText(node_lm, "cwd") @@ -157,7 +157,7 @@ def __processFile(self): try: pos = (posVal[0], posVal[1]) size = (posVal[2], posVal[3]) - except Exception: + except IndexError: pos = None size = None # this happens on Windows when mapwindow is minimized when @@ -2023,7 +2023,7 @@ def _get_value(self, line): """Get value of element""" try: return line.strip(" ").split(" ")[1].strip(" ") - except Exception: + except (IndexError, AttributeError): return "" def _get_element(self, line): diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index c5a5901a814..f3204ecacee 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -208,7 +208,7 @@ def LoadData(self, layer, columns=None, where=None, sql=None): try: # for maps connected via v.external keyId = columns.index(keyColumn) - except Exception: + except ValueError: keyId = -1 # read data @@ -3101,6 +3101,7 @@ class LayerBook(wx.Notebook): def __init__(self, parent, id, parentDialog, style=wx.BK_DEFAULT): wx.Notebook.__init__(self, parent, id, style=style) + self.delet6yeLayer = None self.parent = parent self.parentDialog = parentDialog self.mapDBInfo = self.parentDialog.dbMgrData["mapDBInfo"] @@ -3817,7 +3818,7 @@ def OnAddLayer(self, event): def OnDeleteLayer(self, event): """Delete layer""" try: - layer = int(self.deleteLayer.GetValue()) + layer = int(self.delet6yeLayer.GetValue()) except Exception: return @@ -3868,7 +3869,7 @@ def OnChangeLayer(self, event): except Exception: try: layer = self.mapDBInfo.layers.keys()[0] - except Exception: + except (TypeError, IndexError, AttributeError): return if self.GetCurrentPage() == self.modifyPanel: diff --git a/gui/wxpython/gui_core/dialogs.py b/gui/wxpython/gui_core/dialogs.py index 67ec181082a..2e82442a5b6 100644 --- a/gui/wxpython/gui_core/dialogs.py +++ b/gui/wxpython/gui_core/dialogs.py @@ -1217,7 +1217,7 @@ def _filter(self, data): try: if re.compile(self.flt_pattern).search(dt): flt_data.append(dt) - except Exception: + except (re.error, TypeError): pass return flt_data @@ -1662,7 +1662,7 @@ def OnFilter(self, event): try: if re.compile(event.GetString()).search(layer): list.append(layer) - except Exception: + except (re.error, TypeError): pass list = naturally_sorted(list) diff --git a/gui/wxpython/gui_core/forms.py b/gui/wxpython/gui_core/forms.py index f56df23b838..684ba2446af 100644 --- a/gui/wxpython/gui_core/forms.py +++ b/gui/wxpython/gui_core/forms.py @@ -2019,7 +2019,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar # check wildcard try: fExt = os.path.splitext(p.get("key_desc", ["*.*"])[0])[1] - except Exception: + except (TypeError, IndexError): fExt = None if not fExt: fMask = "*" diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index 1f8e5b39789..82ca129b1eb 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -568,15 +568,15 @@ def _langString(self, k, v): allStr = "%s :" % k.upper() try: allStr += _(" %d translated" % v["good"]) - except Exception: + except (KeyError, TypeError): pass try: allStr += _(" %d fuzzy" % v["fuzzy"]) - except Exception: + except (KeyError, TypeError): pass try: allStr += _(" %d untranslated" % v["bad"]) - except Exception: + except (KeyError, TypeError): pass return allStr diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 098c1b94fb9..59f030b2a93 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -754,7 +754,7 @@ def _validate(self, win): if text: try: datetime.strptime(text, "%Y-%m-%d") - except Exception: + except (TypeError, ValueError): self._notvalid() return False diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index 9866a38e796..b4f8c4bc788 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -596,7 +596,7 @@ def _renderscattplts(self, scatt_ids, cats, cats_attrs): try: self.cat_ids.remove(c) scatt_dt[c]["render"] = True - except Exception: + except (ValueError, KeyError): scatt_dt[c]["render"] = False if self.scatt_mgr.pol_sel_mode[0]: @@ -673,7 +673,7 @@ def ChangePosition(self, cat_id, new_pos): try: pos = self.cats_ids.index(cat_id) - except Exception: + except ValueError: return False if pos > new_pos: diff --git a/gui/wxpython/iscatt/frame.py b/gui/wxpython/iscatt/frame.py index 3a4eda67236..453b980d888 100644 --- a/gui/wxpython/iscatt/frame.py +++ b/gui/wxpython/iscatt/frame.py @@ -249,7 +249,7 @@ def CursorPlotMove(self, x, y, scatt_id): x = int(round(x)) y = int(round(y)) coords = True - except Exception: + except (TypeError, ValueError): coords = False pane = self._getPane(scatt_id) diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index fc0308fc06b..d9d730f85d7 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -1123,7 +1123,7 @@ def GetMenuCmd(self, event): try: cmdlist = cmd.split(" ") - except Exception: # already list? + except AttributeError: # already list? cmdlist = cmd # check list of dummy commands for GUI modules that do not have GRASS diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py index 7dafa504bc8..3f36daf6501 100644 --- a/gui/wxpython/lmgr/layertree.py +++ b/gui/wxpython/lmgr/layertree.py @@ -2005,7 +2005,7 @@ def OnDrop(self, dropTarget, dragItem): # save everything associated with item to drag try: old = dragItem # make sure this member exists - except Exception: + except NameError: return Debug.msg(4, "LayerTree.OnDrop(): layer=%s" % (self.GetItemText(dragItem))) diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py index e8e112a5d40..3d19a3f13a6 100644 --- a/gui/wxpython/location_wizard/wizard.py +++ b/gui/wxpython/location_wizard/wizard.py @@ -1195,15 +1195,15 @@ def OnDText(self, event): self.datumparams = self.parent.datums[self.datum][2] try: self.datumparams.remove("dx=0.0") - except Exception: + except (AttributeError, ValueError): pass try: self.datumparams.remove("dy=0.0") - except Exception: + except (AttributeError, ValueError): pass try: self.datumparams.remove("dz=0.0") - except Exception: + except (AttributeError, ValueError): pass nextButton.Enable(True) @@ -1945,7 +1945,7 @@ def OnText(self, event): self.epsgcode = event.GetString() try: self.epsgcode = int(self.epsgcode) - except Exception: + except (TypeError, ValueError): self.epsgcode = None nextButton = wx.FindWindowById(wx.ID_FORWARD) @@ -2642,7 +2642,7 @@ def __readData(self): try: pparam, datatype, proj4term, desc = line.split(":") self.paramdesc[pparam] = (datatype, proj4term, desc) - except Exception: + except (ValueError, AttributeError): continue f.close() diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 59ad1982e06..455f3ba7add 100644 --- a/gui/wxpython/mapdisp/main.py +++ b/gui/wxpython/mapdisp/main.py @@ -176,7 +176,7 @@ def GetLayersFromCmdFile(self): mapFile = line.split("=", 1)[1].strip() try: k, v = line[2:].strip().split("=", 1) - except Exception: + except (AttributeError, ValueError): pass render_env[k] = v continue diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py index 967e927e423..4002958a9c2 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -1762,7 +1762,7 @@ def Pixel2Cell(self, xyCoords): try: x = int(xyCoords[0]) y = int(xyCoords[1]) - except Exception: + except (TypeError, ValueError, IndexError): return None if self.Map.region["ewres"] > self.Map.region["nsres"]: @@ -1783,7 +1783,7 @@ def Cell2Pixel(self, enCoords): try: east = float(enCoords[0]) north = float(enCoords[1]) - except Exception: + except (TypeError, ValueError, IndexError): return None if self.Map.region["ewres"] > self.Map.region["nsres"]: diff --git a/gui/wxpython/modules/histogram.py b/gui/wxpython/modules/histogram.py index 85e9b4e8c1a..164b8fc9175 100644 --- a/gui/wxpython/modules/histogram.py +++ b/gui/wxpython/modules/histogram.py @@ -258,7 +258,7 @@ def UpdateHistDone(self): return try: id = self.imagedict[self.img] - except Exception: + except (KeyError, AttributeError): return # paint images to PseudoDC diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py index 16e9b96f0e4..ff8dd31227c 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -497,7 +497,7 @@ def OnRun(self, event): if nBandsStr: try: nBands = int(nBandsStr.rstrip("\n")) - except Exception: + except (TypeError, ValueError): pass if nBands < 0: GWarning(_("Unable to determine number of raster bands"), parent=self) diff --git a/gui/wxpython/modules/mcalc_builder.py b/gui/wxpython/modules/mcalc_builder.py index 84319810a73..905981e8522 100644 --- a/gui/wxpython/modules/mcalc_builder.py +++ b/gui/wxpython/modules/mcalc_builder.py @@ -608,7 +608,7 @@ def _addSomething(self, what): if newmcalcstr[-1] != " ": newmcalcstr += " " position_offset += 1 - except Exception: + except (IndexError, TypeError): pass newmcalcstr += what @@ -617,7 +617,7 @@ def _addSomething(self, what): try: if newmcalcstr[-1] != " " and mcalcstr[position] != " ": newmcalcstr += " " - except Exception: + except (IndexError, TypeError): newmcalcstr += " " newmcalcstr += mcalcstr[position:] @@ -632,7 +632,7 @@ def _addSomething(self, what): try: if newmcalcstr[position + position_offset] == " ": position_offset += 1 - except Exception: + except (IndexError, TypeError): pass self.text_mcalc.SetInsertionPoint(position + position_offset) diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index 20df3f75f96..e23032a5f19 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -158,7 +158,7 @@ def SetInitialMaps(self): else: try: selection = layers[0].GetName() - except Exception: + except (IndexError, AttributeError): continue if ltype == "raster": self.FindWindowById(self.win["surface"]["map"]).SetValue(selection) @@ -5066,7 +5066,7 @@ def OnCPlaneChanging(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except Exception: # TODO disabled page + except (IndexError, TypeError, ValueError): # TODO disabled page planeIndex = -1 if event.GetId() in ( @@ -5110,7 +5110,7 @@ def OnCPlaneShading(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except Exception: # TODO disabled page + except (IndexError, TypeError, ValueError): # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex]["shading"] = shading @@ -5125,7 +5125,7 @@ def OnCPlaneReset(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except Exception: # TODO disabled page + except (TypeError, ValueError, IndexError): # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex] = copy.deepcopy( diff --git a/gui/wxpython/vdigit/mapwindow.py b/gui/wxpython/vdigit/mapwindow.py index af14ea41b0a..89c5b534193 100644 --- a/gui/wxpython/vdigit/mapwindow.py +++ b/gui/wxpython/vdigit/mapwindow.py @@ -625,7 +625,7 @@ def OnLeftDownUndo(self, event): ], ) # self.mouse['begin'] = self.Cell2Pixel(self.polycoords[-1]) - except Exception: + except IndexError: pass if action == "editLine": diff --git a/gui/wxpython/wxplot/profile.py b/gui/wxpython/wxplot/profile.py index c1ae12010fa..a41abb546b6 100644 --- a/gui/wxpython/wxplot/profile.py +++ b/gui/wxpython/wxplot/profile.py @@ -248,7 +248,7 @@ def SetupProfile(self): # delete extra first segment point try: self.seglist.pop(0) - except Exception: + except IndexError: pass # diff --git a/lib/init/grass.py b/lib/init/grass.py index 5fdec3b7a2d..94210b9de61 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -154,7 +154,7 @@ def to_text_string(obj, encoding=ENCODING): def try_remove(path): try: os.remove(path) - except: # noqa: E722 + except (FileNotFoundError, PermissionError, IsADirectoryError, OSError): pass @@ -488,7 +488,7 @@ def create_tmp(user, gis_lock): tmpdir = os.path.join(tmp, tmpdir_name) try: os.mkdir(tmpdir, 0o700) - except: # noqa: E722 + except (FileExistsError, FileNotFoundError, PermissionError, OSError): tmp = None if not tmp: @@ -497,7 +497,7 @@ def create_tmp(user, gis_lock): tmpdir = os.path.join(tmp, tmpdir_name) try: os.mkdir(tmpdir, 0o700) - except: # noqa: E722 + except (FileExistsError, FileNotFoundError, PermissionError, OSError): tmp = None if tmp: break @@ -543,7 +543,7 @@ def create_gisrc(tmpdir, gisrcrc): if "UNKNOWN" in s: try_remove(gisrcrc) s = None - except Exception: + except (FileNotFoundError, PermissionError, IsADirectoryError, OSError): s = None # Copy the global grassrc file to the session grassrc file @@ -1847,7 +1847,7 @@ def say_hello(): revision = linerev.split(" ")[1] sys.stderr.write(" (" + revision + ")") - except Exception: + except (FileNotFoundError, PermissionError, IndexError, IOError): pass @@ -2213,7 +2213,7 @@ def print_params(params): try: revision = linerev.split(" ")[1] sys.stdout.write("%s\n" % revision[1:]) - except Exception: + except (IndexError, TypeError, AttributeError): sys.stdout.write("No SVN revision defined\n") elif arg == "version": sys.stdout.write("%s\n" % GRASS_VERSION) diff --git a/locale/grass_po_stats.py b/locale/grass_po_stats.py index 6a839cbafb2..320aeddb470 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -144,7 +144,7 @@ def writejson(stats, outfile): fout.close() try: os.remove("messages.mo") - except Exception: + except (FileNotFoundError, PermissionError, IsADirectoryError, OSError): pass diff --git a/man/build_keywords.py b/man/build_keywords.py index 02710982410..21ab5444963 100644 --- a/man/build_keywords.py +++ b/man/build_keywords.py @@ -81,17 +81,17 @@ def get_module_man_html_file_path(module): try: index_keys = lines.index("

KEYWORDS

\n") + 1 index_desc = lines.index("

NAME

\n") + 1 - except Exception: + except ValueError: continue try: keys = lines[index_keys].split(",") - except Exception: + except (IndexError, TypeError): continue for key in keys: key = key.strip() try: key = key.split(">")[1].split("<")[0] - except Exception: + except (IndexError, AttributeError): pass if not key: exit("Empty keyword from file %s line: %s" % (fname, lines[index_keys])) @@ -104,10 +104,10 @@ def get_module_man_html_file_path(module): for black in blacklist: try: del keywords[black] - except Exception: + except KeyError: try: del keywords[black.lower()] - except Exception: + except (KeyError, TypeError): continue for key in sorted(keywords.keys()): diff --git a/man/build_topics.py b/man/build_topics.py index 3068461c4f0..43956537016 100644 --- a/man/build_topics.py +++ b/man/build_topics.py @@ -24,16 +24,16 @@ try: index_keys = lines.index("

KEYWORDS

\n") + 1 index_desc = lines.index("

NAME

\n") + 1 - except Exception: + except ValueError: continue try: key = lines[index_keys].split(",")[1].strip().replace(" ", "_") key = key.split(">")[1].split("<")[0] - except Exception: + except (IndexError, AttributeError): continue try: desc = lines[index_desc].split("-", 1)[1].strip() - except Exception: + except (IndexError, AttributeError): desc.strip() if key not in keywords.keys(): keywords[key] = {} diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index 51adf26170e..c92c8927901 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -48,7 +48,7 @@ try: import psycopg2 import psycopg2.extras -except Exception: +except ImportError: pass import atexit diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py index ad801666122..1e49e642949 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -17,7 +17,7 @@ import dateutil.parser as parser has_dateutil = True -except Exception: +except ImportError: has_dateutil = False @@ -324,7 +324,7 @@ def modify_datetime( try: dt1 = dt1.replace(year=year + years_to_add, month=residual_months) - except Exception: + except (TypeError, ValueError): raise tdelta_months = dt1 - mydate @@ -351,7 +351,7 @@ def modify_datetime( try: dt1 = dt1.replace(year=year - years_to_remove, month=residual_months) - except Exception: + except (TypeError, ValueError): raise tdelta_months = dt1 - mydate @@ -832,7 +832,7 @@ def check_datetime_string(time_string, use_dateutil=True): try: return datetime.strptime(time_string, time_format) - except Exception: + except (TypeError, ValueError): return _("Unable to parse time string: %s" % time_string) diff --git a/python/grass/temporal/spatial_topology_dataset_connector.py b/python/grass/temporal/spatial_topology_dataset_connector.py index 232373c2180..c9a5e13be65 100644 --- a/python/grass/temporal/spatial_topology_dataset_connector.py +++ b/python/grass/temporal/spatial_topology_dataset_connector.py @@ -118,31 +118,31 @@ def get_number_of_spatial_relations(self): relations = {} try: relations["equivalent"] = len(self._spatial_topology["EQUIVALENT"]) - except Exception: + except (KeyError, TypeError): relations["equivalent"] = 0 try: relations["overlap"] = len(self._spatial_topology["OVERLAP"]) - except Exception: + except (KeyError, TypeError): relations["overlap"] = 0 try: relations["in"] = len(self._spatial_topology["IN"]) - except Exception: + except (KeyError, TypeError): relations["in"] = 0 try: relations["contain"] = len(self._spatial_topology["CONTAIN"]) - except Exception: + except (KeyError, TypeError): relations["contain"] = 0 try: relations["meet"] = len(self._spatial_topology["MEET"]) - except Exception: + except (KeyError, TypeError): relations["meet"] = 0 try: relations["cover"] = len(self._spatial_topology["COVER"]) - except Exception: + except (KeyError, TypeError): relations["cover"] = 0 try: relations["covered"] = len(self._spatial_topology["COVERED"]) - except Exception: + except (KeyError, TypeError): relations["covered"] = 0 return relations diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index f0e1af757ed..ab4fe3adc12 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -442,7 +442,7 @@ try: import ply.lex as lex import ply.yacc as yacc -except Exception: +except ImportError: pass import os diff --git a/python/grass/temporal/temporal_granularity.py b/python/grass/temporal/temporal_granularity.py index 9c60902e3f7..f30fd6b8ba8 100644 --- a/python/grass/temporal/temporal_granularity.py +++ b/python/grass/temporal/temporal_granularity.py @@ -90,19 +90,19 @@ def check_granularity_string(granularity, temporal_type): if temporal_type == "absolute": try: num, unit = granularity.split(" ") - except Exception: + except (TypeError, ValueError): return False if unit not in SUPPORTED_GRAN: return False try: integer = int(num) - except Exception: + except (TypeError, ValueError): return False elif temporal_type == "relative": try: integer = int(granularity) - except Exception: + except (TypeError, ValueError): return False else: return False diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index b3a314b4fd6..8067011f8ed 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -387,7 +387,7 @@ def sub_cmdstring(map_i): else: try: map_sub = map_i.get_id() - except Exception: + except (AttributeError, TypeError): map_sub = map_i return map_sub diff --git a/python/grass/temporal/temporal_topology_dataset_connector.py b/python/grass/temporal/temporal_topology_dataset_connector.py index b905ce25855..61b32472de5 100644 --- a/python/grass/temporal/temporal_topology_dataset_connector.py +++ b/python/grass/temporal/temporal_topology_dataset_connector.py @@ -160,47 +160,47 @@ def get_number_of_temporal_relations(self): relations = {} try: relations["equal"] = len(self._temporal_topology["EQUAL"]) - except Exception: + except (KeyError, TypeError): relations["equal"] = 0 try: relations["follows"] = len(self._temporal_topology["FOLLOWS"]) - except Exception: + except (KeyError, TypeError): relations["follows"] = 0 try: relations["precedes"] = len(self._temporal_topology["PRECEDES"]) - except Exception: + except (KeyError, TypeError): relations["precedes"] = 0 try: relations["overlaps"] = len(self._temporal_topology["OVERLAPS"]) - except Exception: + except (KeyError, TypeError): relations["overlaps"] = 0 try: relations["overlapped"] = len(self._temporal_topology["OVERLAPPED"]) - except Exception: + except (KeyError, TypeError): relations["overlapped"] = 0 try: relations["during"] = len(self._temporal_topology["DURING"]) - except Exception: + except (KeyError, TypeError): relations["during"] = 0 try: relations["contains"] = len(self._temporal_topology["CONTAINS"]) - except Exception: + except (KeyError, TypeError): relations["contains"] = 0 try: relations["starts"] = len(self._temporal_topology["STARTS"]) - except Exception: + except (KeyError, TypeError): relations["starts"] = 0 try: relations["started"] = len(self._temporal_topology["STARTED"]) - except Exception: + except (KeyError, TypeError): relations["started"] = 0 try: relations["finishes"] = len(self._temporal_topology["FINISHES"]) - except Exception: + except (KeyError, TypeError): relations["finishes"] = 0 try: relations["finished"] = len(self._temporal_topology["FINISHED"]) - except Exception: + except (KeyError, TypeError): relations["finished"] = 0 return relations diff --git a/scripts/d.frame/d.frame.py b/scripts/d.frame/d.frame.py index 7471a986df1..e9f96045c6e 100755 --- a/scripts/d.frame/d.frame.py +++ b/scripts/d.frame/d.frame.py @@ -206,7 +206,7 @@ def calculate_frame(frame, at, width, height): """ try: b, t, l, r = list(map(float, at.split(","))) - except Exception: + except (TypeError, ValueError): fatal(_("Invalid frame position: %s") % at) top = round(height - (t / 100.0 * height)) @@ -238,7 +238,7 @@ def create_frame(monitor, frame, at, overwrite=False): width = int(line.split("=", 1)[1].rsplit(" ", 1)[0]) elif "HEIGHT" in line: height = int(line.split("=", 1)[1].rsplit(" ", 1)[0]) - except Exception: + except (TypeError, ValueError, IndexError): pass if width < 0 or height < 0: diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index 368f6ce6078..6e440dfd0ee 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -102,7 +102,7 @@ hasNumPy = False import grass.script as grass - +from grass.exceptions import CalledModuleError def main(): if not hasNumPy: @@ -535,7 +535,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): type="raster", name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), ) - except Exception: + except CalledModuleError: pass @@ -577,7 +577,7 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): grass.run_command( "g.remove", flags="f", quiet=True, type="raster", name=panmatch ) - except Exception: + except CalledModuleError: pass diff --git a/scripts/r.fillnulls/r.fillnulls.py b/scripts/r.fillnulls/r.fillnulls.py index 546eee4a1bc..e87ab0e99cf 100755 --- a/scripts/r.fillnulls/r.fillnulls.py +++ b/scripts/r.fillnulls/r.fillnulls.py @@ -273,7 +273,7 @@ def main(): type="area", quiet=quiet, ) - except Exception: + except CalledModuleError: grass.fatal( _( "abandoned. Removing temporary maps, restoring " @@ -481,7 +481,7 @@ def main(): tmp_rmaps.remove(holename + "_edges") tmp_rmaps.remove(holename + "_dem") tmp_vmaps.remove(holename) - except Exception: + except ValueError: pass grass.warning( _( @@ -545,7 +545,7 @@ def main(): tmp_rmaps.remove(holename + "_grown") tmp_rmaps.remove(holename + "_edges") tmp_rmaps.remove(holename + "_dem") - except Exception: + except ValueError: pass try: grass.run_command( @@ -569,7 +569,7 @@ def main(): ) try: tmp_vmaps.remove(holename) - except Exception: + except ValueError: pass try: grass.run_command( diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py index 95aa758e501..51b98682b70 100755 --- a/scripts/r.in.srtm/r.in.srtm.py +++ b/scripts/r.in.srtm/r.in.srtm.py @@ -230,7 +230,7 @@ def main(): try: zf = zfile.ZipFile(zipfile) zf.extractall() - except Exception: + except (FileNotFoundError, PermissionError, OSError, zipfile.BadZipFile): grass.fatal(_("Unable to unzip file.")) grass.message(_("Converting input file to BIL...")) @@ -275,10 +275,7 @@ def main(): outf.write(proj) outf.close() - try: - grass.run_command("r.in.gdal", input=bilfile, out=tileout) - except Exception: - grass.fatal(_("Unable to import data")) + grass.run_command("r.in.gdal", input=bilfile, out=tileout, errors="fatal") # nice color table if not swbd: diff --git a/scripts/r.in.wms/srs.py b/scripts/r.in.wms/srs.py index c581bc09637..ad877b2fd27 100644 --- a/scripts/r.in.wms/srs.py +++ b/scripts/r.in.wms/srs.py @@ -79,7 +79,7 @@ def __init__(self, srs): # code is always the last value try: self.code = int(values[-1]) - except Exception: + except ValueError: self.code = values[-1] elif len(values) == 2: # it's an authority:code code diff --git a/scripts/r.in.wms/wms_drv.py b/scripts/r.in.wms/wms_drv.py index fa789003053..a6792ee950c 100644 --- a/scripts/r.in.wms/wms_drv.py +++ b/scripts/r.in.wms/wms_drv.py @@ -24,7 +24,7 @@ try: from osgeo import gdal -except Exception: +except ImportError: grass.fatal( _( "Unable to load GDAL Python bindings (requires package 'python-gdal' " diff --git a/scripts/r.in.wms/wms_gdal_drv.py b/scripts/r.in.wms/wms_gdal_drv.py index d6f81bf02ba..5c1b78961dc 100644 --- a/scripts/r.in.wms/wms_gdal_drv.py +++ b/scripts/r.in.wms/wms_gdal_drv.py @@ -17,7 +17,7 @@ try: from osgeo import gdal -except Exception: +except ImportError: grass.fatal( _( "Unable to load GDAL Python bindings (requires package 'python-gdal' being " diff --git a/scripts/v.import/v.import.py b/scripts/v.import/v.import.py index 05fd45d6f30..eebb26e2391 100755 --- a/scripts/v.import/v.import.py +++ b/scripts/v.import/v.import.py @@ -266,7 +266,7 @@ def main(): if OGRdatasource.lower().endswith("gml"): try: from osgeo import gdal - except Exception: + except ImportError: grass.fatal( _( "Unable to load GDAL Python bindings (requires package " @@ -343,7 +343,7 @@ def main(): if OGRdatasource.lower().endswith("gml"): try: from osgeo import gdal - except Exception: + except ImportError: grass.fatal( _( "Unable to load GDAL Python bindings (requires package " diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index c64774aa47c..02a1cf8dd7d 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -77,7 +77,7 @@ def main(): tar = tarfile.TarFile.open(name=input_base, mode="r") try: data_name = tar.getnames()[0] - except Exception: + except (AttributeError, IndexError, tarfile.ReadError): grass.fatal(_("Pack file unreadable")) if flags["p"]: diff --git a/scripts/v.what.strds/v.what.strds.py b/scripts/v.what.strds/v.what.strds.py index c55fe23daa4..adf3462f828 100644 --- a/scripts/v.what.strds/v.what.strds.py +++ b/scripts/v.what.strds/v.what.strds.py @@ -50,7 +50,7 @@ # %end import grass.script as grass -from grass.exceptions import CalledModuleError +from grass.exceptions import CalledModuleError, OpenError ############################################################################ diff --git a/utils/gitlog2changelog.py b/utils/gitlog2changelog.py index a47e8f063ee..955cc663d80 100755 --- a/utils/gitlog2changelog.py +++ b/utils/gitlog2changelog.py @@ -66,7 +66,7 @@ author = authorList[1] author = author[0 : len(author) - 1] authorFound = True - except Exception: + except IndexError: print("Could not parse authorList = '%s'" % (line)) # Match the date line @@ -76,7 +76,7 @@ date = dateList[1] date = date[0 : len(date) - 1] dateFound = True - except Exception: + except (IndexError, TypeError): print("Could not parse dateList = '%s'" % (line)) # The Fossil-IDs are ignored: elif line.startswith(" Fossil-ID:") or line.startswith(" [[SVN:"): From bce6eebb33500a6cccf5f2af1215e8b918082d31 Mon Sep 17 00:00:00 2001 From: mshukun Date: Mon, 3 Jun 2024 15:59:28 -0400 Subject: [PATCH 3/9] `black` --- gui/wxpython/core/settings.py | 9 +++++++-- scripts/i.pansharpen/i.pansharpen.py | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index f01c371adfb..7da80a87511 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -110,8 +110,13 @@ def _generateLocale(self): self.locs.sort() # Add a default choice to not override system locale self.locs.insert(0, "system") - except (KeyError, FileNotFoundError, PermissionError, NotADirectoryError, - OSError): + except ( + KeyError, + FileNotFoundError, + PermissionError, + NotADirectoryError, + OSError, + ): # No NLS self.locs = ["system"] diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index 6e440dfd0ee..c9e61321bee 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -104,6 +104,7 @@ import grass.script as grass from grass.exceptions import CalledModuleError + def main(): if not hasNumPy: grass.fatal(_("Required dependency NumPy not found. Exiting.")) From 9b3b26171212864b191ca798f1bd21a3a5f19cdc Mon Sep 17 00:00:00 2001 From: mshukuno Date: Wed, 5 Jun 2024 18:27:38 -0400 Subject: [PATCH 4/9] Implementing suggested changes from the code review --- lib/init/grass.py | 2 +- scripts/i.pansharpen/i.pansharpen.py | 41 ++++++++++++---------------- scripts/v.unpack/v.unpack.py | 4 +-- scripts/v.what.strds/v.what.strds.py | 2 +- 4 files changed, 22 insertions(+), 27 deletions(-) diff --git a/lib/init/grass.py b/lib/init/grass.py index 94210b9de61..004284bf910 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -742,7 +742,7 @@ def set_paths(grass_config_dir): s = p.stdout.read() p.wait() sys_man_path = s.strip() - except Exception: + except (subprocess.TimeoutExpired, subprocess.SubprocessError): pass if sys_man_path: diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index c9e61321bee..a7bc081e011 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -102,7 +102,6 @@ hasNumPy = False import grass.script as grass -from grass.exceptions import CalledModuleError def main(): @@ -455,12 +454,11 @@ def main(): # Cleanup grass.message(_("cleaning up temp files")) - try: - grass.run_command( - "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True - ) - except Exception: - pass + + grass.run_command( + "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True, + errors="ignore" + ) def brovey(pan, ms1, ms2, ms3, out, pid, sproc): @@ -528,16 +526,15 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): pass # Cleanup - try: - grass.run_command( - "g.remove", - flags="f", - quiet=True, - type="raster", - name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), - ) - except CalledModuleError: - pass + grass.run_command( + "g.remove", + flags="f", + quiet=True, + type="raster", + name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), + errors="ignore" + ) + def ihs(pan, ms1, ms2, ms3, out, pid, sproc): @@ -574,12 +571,10 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): ) # Cleanup - try: - grass.run_command( - "g.remove", flags="f", quiet=True, type="raster", name=panmatch - ) - except CalledModuleError: - pass + grass.run_command( + "g.remove", flags="f", quiet=True, type="raster", name=panmatch, errors="ignore" + ) + def pca(pan, ms1, ms2, ms3, out, pid, sproc): diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index 02a1cf8dd7d..5b1de7bc0f9 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -77,8 +77,8 @@ def main(): tar = tarfile.TarFile.open(name=input_base, mode="r") try: data_name = tar.getnames()[0] - except (AttributeError, IndexError, tarfile.ReadError): - grass.fatal(_("Pack file unreadable")) + except (AttributeError, IndexError, tarfile.ReadError) as error: + grass.fatal(_("Pack file unreadable: {error}").format(error=error)) if flags["p"]: # print proj info and exit diff --git a/scripts/v.what.strds/v.what.strds.py b/scripts/v.what.strds/v.what.strds.py index adf3462f828..c55fe23daa4 100644 --- a/scripts/v.what.strds/v.what.strds.py +++ b/scripts/v.what.strds/v.what.strds.py @@ -50,7 +50,7 @@ # %end import grass.script as grass -from grass.exceptions import CalledModuleError, OpenError +from grass.exceptions import CalledModuleError ############################################################################ From 21b41994b75f67b66106b92602d276176b45008a Mon Sep 17 00:00:00 2001 From: mshukuno Date: Mon, 10 Jun 2024 13:37:35 -0400 Subject: [PATCH 5/9] Implementing suggested changes from the code review --- lib/init/grass.py | 4 ++-- .../temporal/spatial_topology_dataset_connector.py | 14 +++++++------- scripts/v.unpack/v.unpack.py | 2 +- utils/gitlog2changelog.py | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/init/grass.py b/lib/init/grass.py index 004284bf910..70ccd2e9190 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -742,7 +742,7 @@ def set_paths(grass_config_dir): s = p.stdout.read() p.wait() sys_man_path = s.strip() - except (subprocess.TimeoutExpired, subprocess.SubprocessError): + except Exception: pass if sys_man_path: @@ -2213,7 +2213,7 @@ def print_params(params): try: revision = linerev.split(" ")[1] sys.stdout.write("%s\n" % revision[1:]) - except (IndexError, TypeError, AttributeError): + except IndexError: sys.stdout.write("No SVN revision defined\n") elif arg == "version": sys.stdout.write("%s\n" % GRASS_VERSION) diff --git a/python/grass/temporal/spatial_topology_dataset_connector.py b/python/grass/temporal/spatial_topology_dataset_connector.py index c9a5e13be65..7a3d8a34df2 100644 --- a/python/grass/temporal/spatial_topology_dataset_connector.py +++ b/python/grass/temporal/spatial_topology_dataset_connector.py @@ -118,31 +118,31 @@ def get_number_of_spatial_relations(self): relations = {} try: relations["equivalent"] = len(self._spatial_topology["EQUIVALENT"]) - except (KeyError, TypeError): + except KeyError: relations["equivalent"] = 0 try: relations["overlap"] = len(self._spatial_topology["OVERLAP"]) - except (KeyError, TypeError): + except KeyError: relations["overlap"] = 0 try: relations["in"] = len(self._spatial_topology["IN"]) - except (KeyError, TypeError): + except KeyError: relations["in"] = 0 try: relations["contain"] = len(self._spatial_topology["CONTAIN"]) - except (KeyError, TypeError): + except KeyError: relations["contain"] = 0 try: relations["meet"] = len(self._spatial_topology["MEET"]) - except (KeyError, TypeError): + except KeyError: relations["meet"] = 0 try: relations["cover"] = len(self._spatial_topology["COVER"]) - except (KeyError, TypeError): + except KeyError: relations["cover"] = 0 try: relations["covered"] = len(self._spatial_topology["COVERED"]) - except (KeyError, TypeError): + except KeyError: relations["covered"] = 0 return relations diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index 5b1de7bc0f9..8a6353657ee 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -77,7 +77,7 @@ def main(): tar = tarfile.TarFile.open(name=input_base, mode="r") try: data_name = tar.getnames()[0] - except (AttributeError, IndexError, tarfile.ReadError) as error: + except (AttributeError, IndexError, tarfile.TarError) as error: grass.fatal(_("Pack file unreadable: {error}").format(error=error)) if flags["p"]: diff --git a/utils/gitlog2changelog.py b/utils/gitlog2changelog.py index 955cc663d80..656c462ddd6 100755 --- a/utils/gitlog2changelog.py +++ b/utils/gitlog2changelog.py @@ -76,7 +76,7 @@ date = dateList[1] date = date[0 : len(date) - 1] dateFound = True - except (IndexError, TypeError): + except IndexError: print("Could not parse dateList = '%s'" % (line)) # The Fossil-IDs are ignored: elif line.startswith(" Fossil-ID:") or line.startswith(" [[SVN:"): From 0f5a6894a357e17f1f9542f3659ef19c2e2387b8 Mon Sep 17 00:00:00 2001 From: mshukuno Date: Mon, 10 Jun 2024 13:40:21 -0400 Subject: [PATCH 6/9] Remove AttributeError --- gui/wxpython/location_wizard/wizard.py | 8 ++++---- gui/wxpython/modules/histogram.py | 2 +- man/build_keywords.py | 2 +- man/build_topics.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py index 3d19a3f13a6..72561c308d4 100644 --- a/gui/wxpython/location_wizard/wizard.py +++ b/gui/wxpython/location_wizard/wizard.py @@ -1195,15 +1195,15 @@ def OnDText(self, event): self.datumparams = self.parent.datums[self.datum][2] try: self.datumparams.remove("dx=0.0") - except (AttributeError, ValueError): + except ValueError: pass try: self.datumparams.remove("dy=0.0") - except (AttributeError, ValueError): + except ValueError: pass try: self.datumparams.remove("dz=0.0") - except (AttributeError, ValueError): + except ValueError: pass nextButton.Enable(True) @@ -2642,7 +2642,7 @@ def __readData(self): try: pparam, datatype, proj4term, desc = line.split(":") self.paramdesc[pparam] = (datatype, proj4term, desc) - except (ValueError, AttributeError): + except ValueError: continue f.close() diff --git a/gui/wxpython/modules/histogram.py b/gui/wxpython/modules/histogram.py index 164b8fc9175..dfe0260afaa 100644 --- a/gui/wxpython/modules/histogram.py +++ b/gui/wxpython/modules/histogram.py @@ -258,7 +258,7 @@ def UpdateHistDone(self): return try: id = self.imagedict[self.img] - except (KeyError, AttributeError): + except KeyError: return # paint images to PseudoDC diff --git a/man/build_keywords.py b/man/build_keywords.py index 21ab5444963..5988ae0fc17 100644 --- a/man/build_keywords.py +++ b/man/build_keywords.py @@ -91,7 +91,7 @@ def get_module_man_html_file_path(module): key = key.strip() try: key = key.split(">")[1].split("<")[0] - except (IndexError, AttributeError): + except IndexError: pass if not key: exit("Empty keyword from file %s line: %s" % (fname, lines[index_keys])) diff --git a/man/build_topics.py b/man/build_topics.py index 43956537016..6be041efa16 100644 --- a/man/build_topics.py +++ b/man/build_topics.py @@ -29,11 +29,11 @@ try: key = lines[index_keys].split(",")[1].strip().replace(" ", "_") key = key.split(">")[1].split("<")[0] - except (IndexError, AttributeError): + except IndexError: continue try: desc = lines[index_desc].split("-", 1)[1].strip() - except (IndexError, AttributeError): + except IndexError: desc.strip() if key not in keywords.keys(): keywords[key] = {} From cf4f4b13331ac1310b5cdcabf0a63b113f41462c Mon Sep 17 00:00:00 2001 From: mshukuno Date: Mon, 10 Jun 2024 13:40:38 -0400 Subject: [PATCH 7/9] Update exceptions --- gui/wxpython/mapdisp/main.py | 2 +- python/grass/temporal/temporal_raster_base_algebra.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 455f3ba7add..9eacf7594d3 100644 --- a/gui/wxpython/mapdisp/main.py +++ b/gui/wxpython/mapdisp/main.py @@ -176,7 +176,7 @@ def GetLayersFromCmdFile(self): mapFile = line.split("=", 1)[1].strip() try: k, v = line[2:].strip().split("=", 1) - except (AttributeError, ValueError): + except (ValueError, IndexError): pass render_env[k] = v continue diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index 8067011f8ed..01be35c902a 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -387,7 +387,7 @@ def sub_cmdstring(map_i): else: try: map_sub = map_i.get_id() - except (AttributeError, TypeError): + except AttributeError: map_sub = map_i return map_sub From a5685146fe907370904d6ab63233535ee2482838 Mon Sep 17 00:00:00 2001 From: mshukuno Date: Mon, 10 Jun 2024 13:41:33 -0400 Subject: [PATCH 8/9] Reformat with `black` --- scripts/i.pansharpen/i.pansharpen.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index a7bc081e011..08bd52dee44 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -456,8 +456,12 @@ def main(): grass.message(_("cleaning up temp files")) grass.run_command( - "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True, - errors="ignore" + "g.remove", + flags="f", + type="raster", + pattern="tmp%s*" % pid, + quiet=True, + errors="ignore", ) @@ -532,11 +536,10 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): quiet=True, type="raster", name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), - errors="ignore" + errors="ignore", ) - def ihs(pan, ms1, ms2, ms3, out, pid, sproc): grass.verbose(_("Using IHS<->RGB algorithm")) # transform RGB channels into IHS color space @@ -576,7 +579,6 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): ) - def pca(pan, ms1, ms2, ms3, out, pid, sproc): grass.verbose(_("Using PCA/inverse PCA algorithm")) grass.message(_("Creating PCA images and calculating eigenvectors...")) From 4636a1bdce37535e0a135be771098da162f3a91f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edouard=20Choini=C3=A8re?= <27212526+echoix@users.noreply.github.com> Date: Thu, 17 Oct 2024 03:35:09 +0000 Subject: [PATCH 9/9] style: Fix UP024 - Replace aliased errors with `OSError` --- lib/init/grass.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/init/grass.py b/lib/init/grass.py index bf91f811238..5c0d8132103 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -1510,7 +1510,7 @@ def say_hello(): revision = linerev.split(" ")[1] sys.stderr.write(" (" + revision + ")") - except (FileNotFoundError, PermissionError, IndexError, IOError): + except (OSError, FileNotFoundError, PermissionError, IndexError): pass