diff --git a/.flake8 b/.flake8 index 36ab602783e..18f3bb7536d 100644 --- a/.flake8 +++ b/.flake8 @@ -13,7 +13,6 @@ per-file-ignores = # F405 variable may be undefined, or defined from star imports # E402 module level import not at top of file # E501 line too long - # E722 do not use bare 'except' # W605 invalid escape sequence # F821 undefined name 'unicode' # F841 local variable assigned to but never used diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index cde41710cd9..a33535ca942 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -37,6 +37,7 @@ import grass.script as gs from grass.script import task as gtask +from grass.exceptions import ScriptError from grass.pydispatch.signal import Signal @@ -688,7 +689,7 @@ def load_source(modname, filename): 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 941d21879cd..2ea7a1d0ab0 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -1228,7 +1228,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 05c6579e636..7d21d04b260 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -109,7 +109,13 @@ 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"] diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index b04d2e73c12..f1981bca58c 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -24,6 +24,7 @@ from grass.script import core as grass from grass.script import task as gtask +from grass.exceptions import CalledModuleError from grass.app.runtime import get_grass_config_dir from core.gcmd import RunCommand @@ -76,7 +77,7 @@ def GetTempfile(pref=None): if pref: return os.path.join(pref, file) return tempfile - except Exception: + except TypeError: return None @@ -254,7 +255,7 @@ def ListOfCatsToRange(cats): try: cats = list(map(int, cats)) - except ValueError: + except (TypeError, ValueError): return catstr i = 0 @@ -575,7 +576,7 @@ def GetListOfLocations(dbase): os.path.join(location, "*") ): listOfLocations.append(os.path.basename(location)) - except OSError: + except (TypeError, FileNotFoundError, PermissionError, NotADirectoryError): pass ListSortLower(listOfLocations) @@ -628,7 +629,7 @@ def _getGDALFormats(): """Get dictionary of available GDAL drivers""" try: ret = grass.read_command("r.in.gdal", quiet=True, flags="f") - except grass.CalledModuleError: + except CalledModuleError: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) @@ -638,7 +639,7 @@ def _getOGRFormats(): """Get dictionary of available OGR drivers""" try: ret = grass.read_command("v.in.ogr", quiet=True, flags="f") - except grass.CalledModuleError: + 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 dd460a68195..a0c5df320af 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -2007,7 +2007,7 @@ def _get_value(self, line): """Get value of element""" try: return line.strip(" ").split(" ")[1].strip(" ") - except IndexError: + except (IndexError, AttributeError): return "" def _get_element(self, line): diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index 20ddbc47f25..3905acb1d73 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -3075,6 +3075,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"] @@ -3839,7 +3840,7 @@ def OnChangeLayer(self, event): except ValueError: try: layer = list(self.mapDBInfo.layers.keys())[0] - except IndexError: + 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 19e430d605e..60581564f04 100644 --- a/gui/wxpython/gui_core/dialogs.py +++ b/gui/wxpython/gui_core/dialogs.py @@ -1209,7 +1209,7 @@ def _filter(self, data): try: if re.compile(self.flt_pattern).search(dt): flt_data.append(dt) - except re.error: + except (re.error, TypeError): pass return flt_data @@ -1646,7 +1646,7 @@ def OnFilter(self, event): try: if re.compile(event.GetString()).search(layer): list.append(layer) - except re.error: + 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 7172835f001..0526015d045 100644 --- a/gui/wxpython/gui_core/forms.py +++ b/gui/wxpython/gui_core/forms.py @@ -1994,7 +1994,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 IndexError: + 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 0c4f6cdadfb..7189a97dd4b 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -566,15 +566,15 @@ def _langString(self, k, v): allStr = "%s :" % k.upper() try: allStr += _(" %d translated") % v["good"] - except KeyError: + except (KeyError, TypeError): pass try: allStr += _(" %d fuzzy") % v["fuzzy"] - except KeyError: + except (KeyError, TypeError): pass try: allStr += _(" %d untranslated") % v["bad"] - except KeyError: + except (KeyError, TypeError): pass return allStr diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 40c9e6c5e19..6ade30d1278 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -750,7 +750,7 @@ def _validate(self, win): if text: try: datetime.strptime(text, "%Y-%m-%d") - except ValueError: + except (TypeError, ValueError): self._notvalid() return False diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index 6a5bcb6bb9e..41a32e9b4ab 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -592,7 +592,7 @@ def _renderscattplts(self, scatt_ids, cats, cats_attrs): try: self.cat_ids.remove(c) scatt_dt[c]["render"] = True - except ValueError: + except (ValueError, KeyError): scatt_dt[c]["render"] = False if self.scatt_mgr.pol_sel_mode[0]: diff --git a/gui/wxpython/iscatt/frame.py b/gui/wxpython/iscatt/frame.py index 542d8acc2c3..1bd2900123c 100644 --- a/gui/wxpython/iscatt/frame.py +++ b/gui/wxpython/iscatt/frame.py @@ -246,7 +246,7 @@ def CursorPlotMove(self, x, y, scatt_id): x = round(x) y = round(y) coords = True - except TypeError: + except (TypeError, ValueError): coords = False pane = self._getPane(scatt_id) diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py index 41d309178f8..fc6e1f48798 100644 --- a/gui/wxpython/location_wizard/wizard.py +++ b/gui/wxpython/location_wizard/wizard.py @@ -614,7 +614,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() @@ -1184,15 +1184,15 @@ def OnDText(self, event): self.datumparams = self.parent.datums[self.datum][2] try: self.datumparams.remove("dx=0.0") - except: + except ValueError: pass try: self.datumparams.remove("dy=0.0") - except: + except ValueError: pass try: self.datumparams.remove("dz=0.0") - except: + except ValueError: pass nextButton.Enable(True) @@ -1207,7 +1207,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() @@ -1388,7 +1388,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() @@ -1930,7 +1930,7 @@ def OnText(self, event): self.epsgcode = event.GetString() try: self.epsgcode = int(self.epsgcode) - except: + except (TypeError, ValueError): self.epsgcode = None nextButton = wx.FindWindowById(wx.ID_FORWARD) @@ -2555,7 +2555,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() @@ -2617,7 +2617,7 @@ def __readData(self): try: pparam, datatype, proj4term, desc = line.split(":") self.paramdesc[pparam] = (datatype, proj4term, desc) - except: + except ValueError: continue f.close() diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 6449bc35d7c..a19c79b5780 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 (ValueError, IndexError): pass render_env[k] = v continue diff --git a/gui/wxpython/mapwin/base.py b/gui/wxpython/mapwin/base.py index c05cc8f840b..260ad60b173 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 e30bf99414c..6692afced54 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -1033,7 +1033,7 @@ def _updateMFinished(self, renderVector=True): for item in self.graphicsSetList: try: item.Draw() - except: + except Exception: GError( parent=self, message=_( @@ -1185,7 +1185,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) @@ -1202,7 +1202,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) @@ -1744,13 +1744,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( @@ -1772,7 +1772,7 @@ def Pixel2Cell(self, xyCoords): try: x = int(xyCoords[0]) y = int(xyCoords[1]) - except: + except (TypeError, ValueError, IndexError): return None if self.Map.region["ewres"] > self.Map.region["nsres"]: @@ -1793,7 +1793,7 @@ def Cell2Pixel(self, enCoords): try: east = float(enCoords[0]) north = float(enCoords[1]) - except: + except (TypeError, ValueError, IndexError): 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/import_export.py b/gui/wxpython/modules/import_export.py index db4e3b517a2..7b3d3482523 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -521,7 +521,7 @@ def OnRun(self, event): if nBandsStr: try: nBands = int(nBandsStr.rstrip("\n")) - except ValueError: + 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 4294a9730de..9476e9f0acb 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 IndexError: + except (IndexError, TypeError): pass newmcalcstr += what @@ -617,7 +617,7 @@ def _addSomething(self, what): try: if newmcalcstr[-1] != " " and mcalcstr[position] != " ": newmcalcstr += " " - except IndexError: + 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 IndexError: + 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 a56a062f6f6..530ad453353 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -4916,7 +4916,7 @@ def OnCPlaneChanging(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except (ValueError, IndexError): # TODO disabled page + except (ValueError, IndexError, TypeError): # TODO disabled page planeIndex = -1 if event.GetId() in ( @@ -4958,7 +4958,7 @@ def OnCPlaneShading(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except (ValueError, IndexError): # TODO disabled page + except (ValueError, IndexError, TypeError): # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex]["shading"] = shading @@ -4973,7 +4973,7 @@ def OnCPlaneReset(self, event): plane = self.FindWindowById(self.win["cplane"]["planes"]).GetStringSelection() try: planeIndex = int(plane.split()[-1]) - 1 - except (ValueError, IndexError): # TODO disabled page + except (ValueError, IndexError, TypeError): # TODO disabled page planeIndex = -1 self.mapWindow.cplanes[planeIndex] = copy.deepcopy( diff --git a/gui/wxpython/vdigit/dialogs.py b/gui/wxpython/vdigit/dialogs.py index 494f8f66acc..3cfc8b8cbe4 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 824ff68fc3e..89ee1e84dbe 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 IndexError: 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 @@ -1095,7 +1095,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 8f7b46644c8..2e3a0d745aa 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/lib/init/grass.py b/lib/init/grass.py index 6e9dcbf7a58..a1e50af63bb 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -110,7 +110,7 @@ def try_remove(path): try: os.remove(path) - except: # noqa: E722 + except (FileNotFoundError, PermissionError, IsADirectoryError, OSError): pass @@ -424,7 +424,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: @@ -433,7 +433,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 @@ -479,7 +479,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 @@ -1496,7 +1496,7 @@ def say_hello(): revision = linerev.split(" ")[1] sys.stderr.write(" (" + revision + ")") - except Exception: + except (OSError, FileNotFoundError, PermissionError, IndexError): pass @@ -1859,7 +1859,7 @@ def print_params(params): try: revision = linerev.split(" ")[1] sys.stdout.write("%s\n" % revision[1:]) - except Exception: + except IndexError: 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 bfae49629d3..09fc201e2fa 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -145,7 +145,7 @@ def writejson(stats, outfile): fout.close() try: os.remove("messages.mo") - except OSError: + except (FileNotFoundError, PermissionError, IsADirectoryError, OSError): pass diff --git a/man/build_keywords.py b/man/build_keywords.py index 546eed62f37..c0f8bba8af9 100644 --- a/man/build_keywords.py +++ b/man/build_keywords.py @@ -92,13 +92,13 @@ def build_keywords(ext): # TODO maybe move to Python re (regex) try: index_keys = lines.index("

KEYWORDS

\n") + 1 - except Exception: + except ValueError: continue try: keys = [] for k in lines[index_keys].split(","): keys.append(k.strip().split(">")[1].split("<")[0]) - except Exception: + except (IndexError, TypeError): continue else: keys = [] @@ -117,10 +117,10 @@ def build_keywords(ext): 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 484f093cc3e..5074d30cbd7 100644 --- a/man/build_topics.py +++ b/man/build_topics.py @@ -47,7 +47,7 @@ def build_topics(ext): # expecting markdown index_keys = lines.index("### KEYWORDS\n") + 3 index_desc = lines.index("## NAME\n") + 2 - except Exception: + except ValueError: continue try: if ext == "html": @@ -56,11 +56,11 @@ def build_topics(ext): else: # expecting markdown key = lines[index_keys].split("]")[0].lstrip("[") - except Exception: + except IndexError: continue try: desc = lines[index_desc].split("-", 1)[1].strip() - except Exception: + except IndexError: desc.strip() if key not in keywords.keys(): diff --git a/python/grass/temporal/abstract_space_time_dataset.py b/python/grass/temporal/abstract_space_time_dataset.py index 74e38c12e6e..47828943bf9 100644 --- a/python/grass/temporal/abstract_space_time_dataset.py +++ b/python/grass/temporal/abstract_space_time_dataset.py @@ -2463,7 +2463,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/core.py b/python/grass/temporal/core.py index 73cba84b6d3..316142238ed 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -52,7 +52,7 @@ try: import psycopg2 import psycopg2.extras -except: +except ImportError: pass import atexit @@ -414,7 +414,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: @@ -1501,7 +1501,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}) @@ -1544,7 +1544,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 2ce435ccf9f..75518512c5f 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -20,7 +20,7 @@ from dateutil import parser has_dateutil = True -except: +except ImportError: has_dateutil = False @@ -799,7 +799,7 @@ def check_datetime_string(time_string: str, use_dateutil: bool = True): try: return datetime.strptime(time_string, time_format) - except: + 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 005ef2fcc45..dd5c64fc045 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 KeyError: relations["equivalent"] = 0 try: relations["overlap"] = len(self._spatial_topology["OVERLAP"]) - except: + except KeyError: relations["overlap"] = 0 try: relations["in"] = len(self._spatial_topology["IN"]) - except: + except KeyError: relations["in"] = 0 try: relations["contain"] = len(self._spatial_topology["CONTAIN"]) - except: + except KeyError: relations["contain"] = 0 try: relations["meet"] = len(self._spatial_topology["MEET"]) - except: + except KeyError: relations["meet"] = 0 try: relations["cover"] = len(self._spatial_topology["COVER"]) - except: + except KeyError: relations["cover"] = 0 try: relations["covered"] = len(self._spatial_topology["COVERED"]) - except: + except KeyError: relations["covered"] = 0 return relations diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index 4a01af910cc..e8955a83e54 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -445,7 +445,7 @@ try: from ply import lex, yacc -except: +except ImportError: pass import copy @@ -2857,7 +2857,7 @@ def p_t_var_expr_td_hash(self, t) -> None: 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 537868eee31..a3b6d09bbec 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) -> bool: if temporal_type == "absolute": try: num, unit = granularity.split(" ") - except: + except (TypeError, ValueError): return False if unit not in SUPPORTED_GRAN: return False try: int(num) - except: + except (TypeError, ValueError): return False elif temporal_type == "relative": try: int(granularity) - except: + except (TypeError, ValueError): return False else: return False diff --git a/python/grass/temporal/temporal_topology_dataset_connector.py b/python/grass/temporal/temporal_topology_dataset_connector.py index 284271cf031..f832729b569 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 KeyError: + except (KeyError, TypeError): relations["equal"] = 0 try: relations["follows"] = len(self._temporal_topology["FOLLOWS"]) - except KeyError: + except (KeyError, TypeError): relations["follows"] = 0 try: relations["precedes"] = len(self._temporal_topology["PRECEDES"]) - except KeyError: + except (KeyError, TypeError): relations["precedes"] = 0 try: relations["overlaps"] = len(self._temporal_topology["OVERLAPS"]) - except KeyError: + except (KeyError, TypeError): relations["overlaps"] = 0 try: relations["overlapped"] = len(self._temporal_topology["OVERLAPPED"]) - except KeyError: + except (KeyError, TypeError): relations["overlapped"] = 0 try: relations["during"] = len(self._temporal_topology["DURING"]) - except KeyError: + except (KeyError, TypeError): relations["during"] = 0 try: relations["contains"] = len(self._temporal_topology["CONTAINS"]) - except KeyError: + except (KeyError, TypeError): relations["contains"] = 0 try: relations["starts"] = len(self._temporal_topology["STARTS"]) - except KeyError: + except (KeyError, TypeError): relations["starts"] = 0 try: relations["started"] = len(self._temporal_topology["STARTED"]) - except KeyError: + except (KeyError, TypeError): relations["started"] = 0 try: relations["finishes"] = len(self._temporal_topology["FINISHES"]) - except KeyError: + except (KeyError, TypeError): relations["finishes"] = 0 try: relations["finished"] = len(self._temporal_topology["FINISHED"]) - except KeyError: + 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 165dd712648..bc4a508053a 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 ValueError: + 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 (ValueError, IndexError): + 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 730701bfb91..4ae241dd28f 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -455,12 +455,15 @@ def main(): # Cleanup gs.message(_("cleaning up temp files")) - try: - gs.run_command( - "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True - ) - except CalledModuleError: - pass + + gs.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 +531,14 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): pass # Cleanup - try: - gs.run_command( - "g.remove", - flags="f", - quiet=True, - type="raster", - name="%s,%s,%s" % (panmatch1, panmatch2, panmatch3), - ) - except CalledModuleError: - pass + gs.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): @@ -575,7 +576,14 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): # Cleanup try: - gs.run_command("g.remove", flags="f", quiet=True, type="raster", name=panmatch) + gs.run_command( + "g.remove", + flags="f", + quiet=True, + type="raster", + name=panmatch, + errors="ignore", + ) except CalledModuleError: pass diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py index 49c7cef9758..e14a3443096 100755 --- a/scripts/r.in.srtm/r.in.srtm.py +++ b/scripts/r.in.srtm/r.in.srtm.py @@ -228,7 +228,13 @@ def main(): try: zf = zfile.ZipFile(zipfile) zf.extractall() - except (zfile.BadZipfile, zfile.LargeZipFile, PermissionError): + except ( + zfile.BadZipfile, + zfile.LargeZipFile, + FileNotFoundError, + PermissionError, + OSError, + ): gs.fatal(_("Unable to unzip file.")) gs.message(_("Converting input file to BIL...")) @@ -274,7 +280,7 @@ def main(): outf.close() try: - gs.run_command("r.in.gdal", input=bilfile, out=tileout) + gs.run_command("r.in.gdal", input=bilfile, out=tileout, errors="fatal") except CalledModuleError: gs.fatal(_("Unable to import data")) diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index 7baa1042ccd..147fb323e22 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 IndexError: - grass.fatal(_("Pack file unreadable")) + except (AttributeError, IndexError, tarfile.TarError) as error: + grass.fatal(_("Pack file unreadable: {error}").format(error=error)) if flags["p"]: # print proj info and exit diff --git a/utils/gitlog2changelog.py b/utils/gitlog2changelog.py index f878041ca83..1c6b41848da 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 as e: + except IndexError as e: print(f"Could not parse authorList = '{line}'. Error: {e!s}") # Match the date line @@ -76,7 +76,7 @@ date = dateList[1] date = date[0 : len(date) - 1] dateFound = True - except Exception as e: + except IndexError as e: print(f"Could not parse dateList = '{line}'. Error: {e!s}") # The Fossil-IDs, svn-id, ad sign off lines are ignored: elif (