eric6/Utilities/__init__.py

changeset 8243
cc717c2ae956
parent 8240
93b8a353c4bf
child 8258
82b608e352ec
--- a/eric6/Utilities/__init__.py	Thu Apr 15 16:52:05 2021 +0200
+++ b/eric6/Utilities/__init__.py	Thu Apr 15 18:11:24 2021 +0200
@@ -221,7 +221,7 @@
     @param text byte text to decode (bytes)
     @return tuple of decoded text and encoding (string, string)
     """
-    try:
+    with contextlib.suppress(UnicodeError, LookupError):
         if text.startswith(BOM_UTF8):
             # UTF-8 with BOM
             return str(text[len(BOM_UTF8):], 'utf-8'), 'utf-8-bom'
@@ -234,14 +234,10 @@
         coding = get_codingBytes(text)
         if coding:
             return str(text, coding), coding
-    except (UnicodeError, LookupError):
-        pass
     
     # Assume UTF-8
-    try:
+    with contextlib.suppress(UnicodeError, LookupError):
         return str(text, 'utf-8'), 'utf-8-guessed'
-    except (UnicodeError, LookupError):
-        pass
     
     guess = None
     if Preferences.getEditor("AdvancedEncodingDetection"):
@@ -262,11 +258,9 @@
             pass
     
     # Try default encoding
-    try:
+    with contextlib.suppress(UnicodeError, LookupError):
         codec = Preferences.getEditor("DefaultEncoding")
         return str(text, codec), '{0}-default'.format(codec)
-    except (UnicodeError, LookupError):
-        pass
     
     if (
         Preferences.getEditor("AdvancedEncodingDetection") and
@@ -274,11 +268,9 @@
         guess['encoding'] is not None
     ):
         # Use the guessed one even if confidence level is low
-        try:
+        with contextlib.suppress(UnicodeError, LookupError):
             codec = guess['encoding'].lower()
             return str(text, codec), '{0}-guessed'.format(codec)
-        except (UnicodeError, LookupError):
-            pass
     
     # Assume UTF-8 loosing information
     return str(text, "utf-8", "ignore"), 'utf-8-ignore'
@@ -295,16 +287,14 @@
     with open(filename, "rb") as f:
         text = f.read()
     if encoding:
-        try:
+        with contextlib.suppress(UnicodeError, LookupError):
             return str(text, encoding), '{0}-selected'.format(encoding)
-        except (UnicodeError, LookupError):
-            pass
+        
         # Try default encoding
-        try:
+        with contextlib.suppress(UnicodeError, LookupError):
             codec = Preferences.getEditor("DefaultEncoding")
             return str(text, codec), '{0}-default'.format(codec)
-        except (UnicodeError, LookupError):
-            pass
+        
         # Assume UTF-8 loosing information
         return str(text, "utf-8", "ignore"), 'utf-8-ignore'
     else:
@@ -364,12 +354,10 @@
                 raise CodingError(coding)
         else:
             if forcedEncoding:
-                try:
+                with contextlib.suppress(UnicodeError, LookupError):
                     etext, encoding = (
                         text.encode(forcedEncoding), forcedEncoding)
-                except (UnicodeError, LookupError):
-                    # Error: Forced encoding is incorrect, ignore it
-                    pass
+                    # if forced encoding is incorrect, ignore it
             
             if encoding is None:
                 # Try the original encoding
@@ -382,25 +370,19 @@
                         .replace("-guessed", "")
                         .replace("-ignore", "")
                     )
-                    try:
+                    with contextlib.suppress(UnicodeError, LookupError):
                         etext, encoding = text.encode(coding), coding
-                    except (UnicodeError, LookupError):
-                        pass
                 
                 if encoding is None:
                     # Try configured default
-                    try:
+                    with contextlib.suppress(UnicodeError, LookupError):
                         codec = Preferences.getEditor("DefaultEncoding")
                         etext, encoding = text.encode(codec), codec
-                    except (UnicodeError, LookupError):
-                        pass
                     
                     if encoding is None:
                         # Try saving as ASCII
-                        try:
+                        with contextlib.suppress(UnicodeError):
                             etext, encoding = text.encode('ascii'), 'ascii'
-                        except UnicodeError:
-                            pass
                         
                         if encoding is None:
                             # Save as UTF-8 without BOM
@@ -438,7 +420,7 @@
     @return decoded text (string)
     """
     # try UTF with BOM
-    try:
+    with contextlib.suppress(UnicodeError, LookupError):
         if buffer.startswith(BOM_UTF8):
             # UTF-8 with BOM
             return str(buffer[len(BOM_UTF8):], encoding='utf-8')
@@ -448,14 +430,10 @@
         elif buffer.startswith(BOM_UTF32):
             # UTF-32 with BOM
             return str(buffer[len(BOM_UTF32):], encoding='utf-32')
-    except (UnicodeError, LookupError):
-        pass
     
     # try UTF-8
-    try:
+    with contextlib.suppress(UnicodeError):
         return str(buffer, encoding="utf-8")
-    except UnicodeError:
-        pass
     
     # try codec detection
     try:
@@ -1287,7 +1265,7 @@
     else:
         # we are on a Linux or macOS platform
         for mountCommand in ["mount", "/sbin/mount", "/usr/sbin/mount"]:
-            try:
+            with contextlib.suppress(FileNotFoundError):
                 mountOutput = (
                     subprocess.check_output(mountCommand).splitlines()  # secok
                 )
@@ -1308,8 +1286,6 @@
                             break
                     if volumeDirectory:
                         break
-            except FileNotFoundError:
-                pass
     
     if findAll:
         return volumeDirectories
@@ -1892,13 +1868,11 @@
         info.append("  PyQtWebEngine not installed")
     info.append("  QScintilla {0}".format(QSCINTILLA_VERSION_STR))
     info.append("  sip {0}".format(sip_version_str))
-    try:
+    with contextlib.suppress(ImportError):
         from PyQt5 import QtWebEngineWidgets    # __IGNORE_WARNING__
         from WebBrowser.Tools import WebBrowserTools
         chromeVersion = WebBrowserTools.getWebEngineVersions()[0]
         info.append("  WebEngine {0}".format(chromeVersion))
-    except ImportError:
-        pass
     info.append("  {0} {1}".format(Program, Version))
     info.append("")
     info.append("Platform: {0}".format(sys.platform))
@@ -1923,7 +1897,7 @@
     info = []
     app = e5App()
     if app is not None:
-        try:
+        with contextlib.suppress(KeyError):
             pm = app.getObject("PluginManager")
             versions = {}
             for pinfo in pm.getPluginInfos():
@@ -1933,8 +1907,6 @@
             for pluginModuleName in sorted(versions.keys()):
                 info.append("  {0} {1}".format(
                     pluginModuleName, versions[pluginModuleName]))
-        except KeyError:
-            pass
     
     return linesep.join(info)
 
@@ -2007,13 +1979,10 @@
     if finished and proc.exitCode() == 0:
         text = proc.readAllStandardOutput()
         sysPathResult = str(text, "utf-8", "replace").strip()
-        try:
+        with contextlib.suppress(TypeError, ValueError):
             sysPath = json.loads(sysPathResult)
             if "" in sysPath:
                 sysPath.remove("")
-        except (TypeError, ValueError):
-            # ignore faulty results and return empty list
-            pass
     
     return sysPath
 

eric ide

mercurial