From aab9050aad963ef0613bee956ba6de03817e21a5 Mon Sep 17 00:00:00 2001 From: Gilles DAVID Date: Thu, 3 Jun 2021 16:31:58 +0200 Subject: [PATCH] Do not use bare "except:" instruction We are in python3: no more need to inherite classes from object. --- bin/PortManager.py | 10 +-- bin/addToKillList.py | 8 +- bin/appli_gen.py | 4 +- .../salome_tester/salome_instance.py | 4 +- .../salome_tester/salome_test_driver.py | 4 +- .../salome_tester/salome_test_driver_gui.py | 4 +- bin/killSalome.py | 10 +-- bin/killSalomeWithPort.py | 20 ++--- bin/launchConfigureParser.py | 12 +-- bin/nameserver.py | 6 +- bin/orbmodule.py | 2 +- bin/runSalome.py | 16 ++-- bin/runSession.py | 4 +- bin/salomeContext.py | 6 +- bin/salomeContextUtils.py.in | 4 +- bin/salome_utils.py | 51 ++++++------ bin/searchFreePort.py | 2 +- bin/server.py | 2 +- bin/setenv.py | 2 +- doc/salome/tui/pythfilter.py | 4 +- salome_adm/prepare_generating_doc.py | 4 +- src/Container/SALOME_Container.py | 10 +-- src/Container/SALOME_ContainerPy.py | 4 +- src/Container/SALOME_PyNode.py | 20 ++--- src/KERNEL_PY/__init__.py | 10 +-- src/KERNEL_PY/kernel/enumerate.py | 6 +- src/KERNEL_PY/kernel/studyedit.py | 2 +- src/KERNEL_PY/kernel/testdata.py | 2 +- src/KERNEL_PY/salome_iapp.py | 4 +- src/KERNEL_PY/salome_notebook.py | 80 ++++++++++--------- src/KERNEL_PY/salome_version.py | 14 ++-- src/Launcher/launcher_proxy.py | 4 +- src/Logger/Test/TestKiller.py | 6 +- src/NamingService/SALOME_NamingServicePy.py | 2 +- src/SALOMEDS/SALOME_DriverPy.py | 2 +- src/SALOMESDS/SALOMEGlobalVarHelper.py | 10 +-- src/SALOMESDS/SalomeSDSClt.py | 2 +- src/Utils/Utils_Identity.py | 2 +- 38 files changed, 181 insertions(+), 178 deletions(-) diff --git a/bin/PortManager.py b/bin/PortManager.py index 344d4654c..a0b9925a8 100644 --- a/bin/PortManager.py +++ b/bin/PortManager.py @@ -26,7 +26,7 @@ import sys try: import cPickle as pickle #@UnusedImport -except: +except ImportError: import pickle #@Reimport __PORT_MIN_NUMBER = 2810 @@ -117,7 +117,7 @@ def __isNetworkConnectionActiveOnPort(port): from subprocess import Popen, PIPE, STDOUT p = Popen(cmd, stdout=PIPE, stderr=STDOUT) out, err = p.communicate() - except: + except Exception: print("Error when trying to access active network connections.") if err: print(err) print("... Presumably this package is not installed...Please install netstat if available for your distribution.") @@ -133,7 +133,7 @@ def __isNetworkConnectionActiveOnPort(port): else: sock.close() return False - except: + except Exception: import traceback traceback.print_exc() return False @@ -148,7 +148,7 @@ def __isNetworkConnectionActiveOnPort(port): try: p = int(regObj.match(item).group(1)) if p == port: return True - except: + except Exception: pass return False # @@ -168,7 +168,7 @@ def getPort(preferredPort=None): try: with open(config_file, 'rb') as f: config = pickle.load(f) - except: + except Exception: logger.debug("Problem loading PortManager file: %s"%config_file) # In this case config dictionary is reset diff --git a/bin/addToKillList.py b/bin/addToKillList.py index ca31fface..3f892e772 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -55,7 +55,7 @@ def addToKillList(command_pid, command, port=None): try: with open(filedict, 'rb') as fpid: process_ids=pickle.load(fpid) - except: + except Exception: process_ids=[] pass # check if PID is already in dictionary @@ -81,7 +81,7 @@ def addToKillList(command_pid, command, port=None): if not os.path.exists(dir): os.makedirs(dir, 0o777) with open(filedict,'wb') as fpid: pickle.dump(process_ids, fpid) - except: + except Exception: if verbose(): print("addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command )) pass pass @@ -105,7 +105,7 @@ def killList(port=None): try: with open(filedict, 'rb') as fpid: process_ids=pickle.load(fpid) - except: + except Exception: process_ids=[] pass # kill processes @@ -114,7 +114,7 @@ def killList(port=None): for pid, cmd in list(process_id.items()): try: os.kill(int(pid),signal.SIGKILL) - except: + except Exception: print(" ------------------ process %s : %s inexistant"% (pid, cmd[0])) pass pass diff --git a/bin/appli_gen.py b/bin/appli_gen.py index 720505ba0..ace6217d5 100755 --- a/bin/appli_gen.py +++ b/bin/appli_gen.py @@ -210,7 +210,7 @@ def install(prefix, config_file, verbose=0): print(inst.args) print("Configure parser: error in configuration file %s" % filename) pass - except: + except Exception: print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename) pass @@ -223,7 +223,7 @@ def install(prefix, config_file, verbose=0): try: ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake") os.remove(ctest_file) - except: + except Exception: pass for module in _config.get("modules", []): diff --git a/bin/appliskel/salome_tester/salome_instance.py b/bin/appliskel/salome_tester/salome_instance.py index e75d24083..2eaf70d3e 100755 --- a/bin/appliskel/salome_tester/salome_instance.py +++ b/bin/appliskel/salome_tester/salome_instance.py @@ -24,7 +24,7 @@ import os # Example of args: # args=["--gui", "--show-desktop=1", "--splash=0"] # args=["--terminal","--modules=FIELDS,PARAVIS,GUI"] -class SalomeInstance(object): +class SalomeInstance: def __init__(self): self.port = None @@ -53,7 +53,7 @@ class SalomeInstance(object): with open(port_log) as f: salome_instance.port = int(f.readline()) os.remove(port_log) - except: + except Exception: pass return salome_instance diff --git a/bin/appliskel/salome_tester/salome_test_driver.py b/bin/appliskel/salome_tester/salome_test_driver.py index df34662fe..38888491f 100755 --- a/bin/appliskel/salome_tester/salome_test_driver.py +++ b/bin/appliskel/salome_tester/salome_test_driver.py @@ -133,14 +133,14 @@ if __name__ == "__main__": res = processResult(res, out, err) except TimeoutException: print("FAILED : timeout(%s) is reached"%timeout_delay) - except: + except Exception: import traceback traceback.print_exc() pass try: salome_instance.stop() os.kill(pid, signal.SIGTERM) - except: + except Exception: pass if sys.platform == 'win32': timer.cancel() diff --git a/bin/appliskel/salome_tester/salome_test_driver_gui.py b/bin/appliskel/salome_tester/salome_test_driver_gui.py index bdaf2db6b..b43a53361 100755 --- a/bin/appliskel/salome_tester/salome_test_driver_gui.py +++ b/bin/appliskel/salome_tester/salome_test_driver_gui.py @@ -68,13 +68,13 @@ if __name__ == "__main__": salome_instance = SalomeInstance.start(with_gui=True, args=test_and_args) except TimeoutException: print("FAILED : timeout(%s) is reached"%timeout_delay) - except: + except Exception: import traceback traceback.print_exc() pass try: salome_instance.stop() - except: + except Exception: pass if sys.platform == 'win32': timer.cancel() diff --git a/bin/killSalome.py b/bin/killSalome.py index 9f8bd648b..9a8c9a45b 100755 --- a/bin/killSalome.py +++ b/bin/killSalome.py @@ -54,11 +54,11 @@ def killAllPorts(): mo = fnamere.match(f) try: killMyPort(mo.group(1)) - except: + except Exception: pass pass pass - except: + except Exception: pass # provide compatibility with old-style pidict file (not dot-prefixed) #fpidict = getPiDict('(\d*)',hidden=False) @@ -74,17 +74,17 @@ def killAllPorts(): mo = fnamere.match(f) try: killMyPort(mo.group(1)) - except: + except Exception: pass pass pass - except: + except Exception: pass # kill other processes for pid in checkUnkilledProcess(): try: os.kill(pid, signal.SIGKILL) - except: + except Exception: pass pass if sys.platform != 'win32': diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 10135dca5..f00ad1650 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -58,7 +58,7 @@ def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None): # Note: this function is also called with port='#####' !!! try: port = int(port) - except: + except Exception: pass from salome_utils import generateFileName, getLogDir @@ -217,7 +217,7 @@ def shutdownMyPort(port, cleanup=True): time.sleep(1) pass pass - except: + except Exception: pass sys.exit(0) # see (1) pass @@ -242,18 +242,18 @@ def __killMyPort(port, filedict): try: from salome_utils import killpid killpid(pid) - except: + except Exception: if verbose(): print(" ------------------ process %s : %s not found"% (pid, cmd[0])) if pid in checkUnkilledProcess(): try: killpid(pid) - except: + except Exception: pass pass pass # for pid ... pass # for process_id ... # end with - except: + except Exception: print("Cannot find or open SALOME PIDs file for port", port) pass os.remove(filedict) @@ -317,7 +317,7 @@ def killMyPort(port): except ImportError: pass return - except: + except Exception: pass # try to shutdown session normally @@ -354,7 +354,7 @@ def cleanApplication(port): try: filedict=getPiDict(port) os.remove(filedict) - except: + except Exception: #import traceback #traceback.print_exc() pass @@ -385,12 +385,12 @@ def killMyPortSpy(pid, port): import SALOME #@UnresolvedImport @UnusedImport session = ns.Resolve("/Kernel/Session") assert session - except: + except Exception: killMyPort(port) return try: status = session.GetStatSession() - except: + except Exception: # -- session is in naming service but has crash status = None pass @@ -432,7 +432,7 @@ def checkUnkilledProcess(): prc = [prc[i].split(',') for i in range(0, len(prc)) if i % 2 == 0] prc = dict([(int(prc[j][1].replace('"', '')), prc[j][0].replace('"', '')) for j in range(0, len(prc))]) processes.update(prc) - except: + except Exception: pass return processes diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py index 23dd6983c..c7eb5157c 100644 --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -119,7 +119,7 @@ def version(): match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', v ) if match : return match.group( 1 ) - except: + except Exception: pass return '' @@ -325,7 +325,7 @@ class xml_parser: else: if isinstance( strloc, bytes): strloc = strloc.decode().strip() - except: + except Exception: pass return strloc @@ -435,7 +435,7 @@ class xml_parser: pass pass pass - except: + except Exception: if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname) pass @@ -912,7 +912,7 @@ def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None, keepEnvi try: dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside - except: + except Exception: pass _opts = {} # associative array of options to be filled @@ -926,7 +926,7 @@ def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None, keepEnvi try: p = xml_parser(filename, _opts, []) _opts = p.opts - except: + except Exception: if verbose(): print("Configure parser: Error : can not read configuration file %s" % filename) pass @@ -944,7 +944,7 @@ def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None, keepEnvi try: p = xml_parser(user_config, _opts, []) _opts = p.opts - except: + except Exception: if verbose(): print('Configure parser: Error : can not read user configuration file') user_config = "" diff --git a/bin/nameserver.py b/bin/nameserver.py index 58982b877..6a8dabb80 100644 --- a/bin/nameserver.py +++ b/bin/nameserver.py @@ -42,7 +42,7 @@ class NamingServer(Server): upath = getLogDir() try: os.makedirs(upath, mode=0o777) - except: + except Exception: pass if verbose(): print("Name Service... ", end =' ') @@ -66,7 +66,7 @@ class NamingServer(Server): upath = os.path.join(upath, "omniNames_%s"%(aPort)) try: os.mkdir(upath) - except: + except Exception: # print("Can't create " + upath) pass @@ -74,7 +74,7 @@ class NamingServer(Server): for fname in os.listdir(upath): try: os.remove(upath + "/" + fname) - except: + except Exception: pass #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log") diff --git a/bin/orbmodule.py b/bin/orbmodule.py index bf4a22c36..34456fb72 100755 --- a/bin/orbmodule.py +++ b/bin/orbmodule.py @@ -179,7 +179,7 @@ class client: while(1): try: os.kill(thePID,0) - except: + except Exception: raise RuntimeError("Process %d for %s not found" % (thePID,theName)) aCount += 1 anObj = self.Resolve(theName) diff --git a/bin/runSalome.py b/bin/runSalome.py index 518e0c502..619f4dc3b 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -50,7 +50,7 @@ def killLocalPort(): my_port=str(args['port']) try: killMyPort(my_port) - except: + except Exception: print("problem in killLocalPort()") pass pass @@ -65,7 +65,7 @@ def givenPortKill(port): my_port=port try: killMyPort(my_port) - except: + except Exception: print("problem in LocalPortKill(), killMyPort(%s)"%port) pass pass @@ -655,7 +655,7 @@ def startSalome(args, modules_list, modules_root_dir): try: if 'interp' in args: nbaddi = args['interp'] - except: + except Exception: import traceback traceback.print_exc() print("-------------------------------------------------------------") @@ -692,7 +692,7 @@ def useSalome(args, modules_list, modules_root_dir): clt=None try: clt = startSalome(args, modules_list, modules_root_dir) - except: + except Exception: import traceback traceback.print_exc() print() @@ -736,7 +736,7 @@ def useSalome(args, modules_list, modules_root_dir): if not args['gui'] or not args['session_gui']: if args['shutdown_servers']: - class __utils__(object): + class __utils__: def __init__(self, port): self.port = port import killSalomeWithPort @@ -877,7 +877,7 @@ def foreGround(clt, args): status = session.GetStatSession() gui_detected = status.activeGUI session_pid = session.getPID() - except: + except Exception: pass if gui_detected: break @@ -908,7 +908,7 @@ def foreGround(clt, args): try: status = session.GetStatSession() assert status.activeGUI - except: + except Exception: break from time import sleep sleep(dt) @@ -937,7 +937,7 @@ def runSalome(): from ctypes import POINTER, c_int, cast, pythonapi iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int)) test = test and not iflag_ptr.contents.value - except: + except Exception: pass # -- # test = test and os.getenv("SALOME_TEST_MODE", "0") != "1" diff --git a/bin/runSession.py b/bin/runSession.py index c83cf502f..12ece0b7b 100644 --- a/bin/runSession.py +++ b/bin/runSession.py @@ -153,7 +153,7 @@ User "myself" connects to remotemachine to run the script concatenate.py in try: # keep short name for host, for a correct comparison with getShortHostName() later host=host.split('.')[0] - except: + except Exception: pass else: # No running session @@ -220,7 +220,7 @@ def __runLocalSession(command): if proc.returncode != 0: any_error = True error_code = proc.returncode - except: + except Exception: any_error = True pass diff --git a/bin/salomeContext.py b/bin/salomeContext.py index 403cb00de..a8a0247b6 100755 --- a/bin/salomeContext.py +++ b/bin/salomeContext.py @@ -111,7 +111,7 @@ class SalomeContext: try: out, err = subprocess.Popen([modulecmd, "python", "load"] + env_modules, stdout=subprocess.PIPE).communicate() exec(out) # define specific environment variables - except: + except Exception: raise SalomeContextException("Failed to load env modules: %s ..." % ' '.join(env_modules)) pass # @@ -262,7 +262,7 @@ class SalomeContext: path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome", "appliskel")) add_path(path, "PYTHONPATH") - except: + except Exception: pass command, options = self.__parseArguments(args) @@ -477,7 +477,7 @@ class SalomeContext: versions[software.upper()] = version if len(software) > max_len: max_len = len(software) - except: + except Exception: pass pass pass diff --git a/bin/salomeContextUtils.py.in b/bin/salomeContextUtils.py.in index d9b33b50a..e4ca05e7b 100644 --- a/bin/salomeContextUtils.py.in +++ b/bin/salomeContextUtils.py.in @@ -262,7 +262,7 @@ def getScriptsAndArgs(args=None, searchPathList=None): break pass fn.close() - except: + except Exception: pass if not ispython and script_extension == ".py": currentKey = "@PYTHONBIN@ "+currentScript @@ -335,7 +335,7 @@ def setOmniOrbUserPath(): if not os.access(temp_dir, os.W_OK): raise Exception("Unable to get write access to directory: %s"%temp_dir) os.environ["OMNIORB_USER_PATH"] = temp_dir - except: + except Exception: homePath = os.path.realpath(os.path.expanduser('~')) #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS") defaultOmniorbUserPath = homePath diff --git a/bin/salome_utils.py b/bin/salome_utils.py index 61aa30203..fc5c2a1c6 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -45,7 +45,7 @@ __all__ = [ 'generateFileName', 'makeTmpDir', 'uniteFiles', - ] +] # --- @@ -77,16 +77,17 @@ def getORBcfgInfo(): If omniORB configuration file can not be accessed, a list of three empty strings is returned. """ - import os, re - ret = [ "", "", "" ] + import os + import re + ret = ["", "", ""] try: - f = open( os.getenv( "OMNIORB_CONFIG" ) ) - lines = f.readlines() - f.close() - regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" ) - for l in lines: + lines = [] + with open(os.getenv("OMNIORB_CONFIG")) as f: + lines = f.readlines() + regvar = re.compile(r"(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$") + for line in lines: try: - m = regvar.match( l ) + m = regvar.match(line) if m: if m.group(1) is None: ret[0] = "4" @@ -97,11 +98,11 @@ def getORBcfgInfo(): ret[2] = m.group(3) break pass - except: + except Exception: pass pass pass - except: + except Exception: pass return ret @@ -153,7 +154,7 @@ def getHostName(): try: import socket host = socket.gethostname() - except: + except Exception: host = None pass if not host: host = os.getenv("HOSTNAME") @@ -161,7 +162,7 @@ def getHostName(): if not host: host = "unknown" # 'unknown' is default host name try: socket.gethostbyname(host) - except: + except Exception: host = "localhost" pass return host @@ -178,7 +179,7 @@ def getShortHostName(): """ try: return getHostName().split('.')[0] - except: + except Exception: pass return "unknown" # 'unknown' is default host name @@ -205,12 +206,12 @@ def getPortNumber(use_default=True): import os try: return int( os.getenv( "NSPORT" ) ) - except: + except Exception: pass try: port = int( getPortFromORBcfg() ) if port is not None: return port - except: + except Exception: pass if use_default: return 2809 # '2809' is default port number return None @@ -308,7 +309,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None, # auto user name ? if _try_bool( kwargs[kw] ): filename.append( getUserName() ) pass - except: + except Exception: # user name given as parameter filename.append( kwargs[kw] ) pass @@ -319,7 +320,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None, # auto host name ? if _try_bool( kwargs[kw] ): filename.append( getShortHostName() ) pass - except: + except Exception: # host name given as parameter filename.append( kwargs[kw] ) pass @@ -330,7 +331,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None, # auto port number ? if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) ) pass - except: + except Exception: # port number given as parameter filename.append( str( kwargs[kw] ) ) pass @@ -341,7 +342,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None, # auto application name ? if _try_bool( kwargs[kw] ): filename.append( getAppName() ) pass - except: + except Exception: # application name given as parameter filename.append( kwargs[kw] ) pass @@ -404,7 +405,7 @@ def makeTmpDir( path, mode=0o777 ): try: os.mkdir(p, mode) os.chmod(p, mode) - except: + except Exception: pass # --- @@ -475,7 +476,7 @@ def verbose(): try: from os import getenv _verbose = int(getenv('SALOME_VERBOSE')) - except: + except Exception: _verbose = 0 pass # @@ -499,7 +500,7 @@ def killpid(pid, sig = 9): Parameters: - pid : PID of process - sig : signal for sending - Possible values of signals: + Possible values of signals: 9 means kill the process 0 only check existing of the process NOTE: Other values are not processed on Windows @@ -575,7 +576,7 @@ def getOmniNamesPid(port): allProc = proc.communicate()[0].decode() # find Pid of omniNames pid = re.findall(r'Caption=.*omniNames.*\n?CommandLine=.*omniNames.*\D%s\D.*\n?ProcessId=(\d*)'%(port),allProc)[0] - else: + else: cmd = "ps -eo pid,command | grep -v grep | grep -E \"omniNames.*%s\" | awk '{print $1}'"%(port) proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) pid = proc.communicate()[0] @@ -591,7 +592,7 @@ def killOmniNames(port): try: pid = getOmniNamesPid(port) if pid: killpid(pid) - except: + except Exception: pass pass # -- diff --git a/bin/searchFreePort.py b/bin/searchFreePort.py index 28df90ba4..31705e9a7 100644 --- a/bin/searchFreePort.py +++ b/bin/searchFreePort.py @@ -58,7 +58,7 @@ def __setup_config(nsport, args, save_config): os.symlink(omniorb_config, last_running_config) pass pass - except: + except Exception: pass # # diff --git a/bin/server.py b/bin/server.py index 70527845c..2d30b82ba 100644 --- a/bin/server.py +++ b/bin/server.py @@ -111,7 +111,7 @@ class Server: try: os.kill(childpid,0) return childpid - except: + except Exception: return None #first child diff --git a/bin/setenv.py b/bin/setenv.py index 655586619..62eee95c3 100755 --- a/bin/setenv.py +++ b/bin/setenv.py @@ -210,7 +210,7 @@ def set_env(args, modules_list, modules_root_dir, silent=False, keepEnvironment= mod=__import__(module.lower()+"_setenv") mod.set_env(args) pass - except: + except Exception: pass pass pass diff --git a/doc/salome/tui/pythfilter.py b/doc/salome/tui/pythfilter.py index 4d63a1123..113581d93 100755 --- a/doc/salome/tui/pythfilter.py +++ b/doc/salome/tui/pythfilter.py @@ -526,12 +526,12 @@ def convert(srcpath, destpath): if os.path.isdir(dname): try: shutil.rmtree(dname) - except: + except Exception: print("Can't remove obsolete directory '%s'"%dname) else: try: os.remove(dname) - except: + except Exception: print("Can't remove obsolete file '%s'"%dname) return count diff --git a/salome_adm/prepare_generating_doc.py b/salome_adm/prepare_generating_doc.py index fed5b6ee3..7acad293e 100755 --- a/salome_adm/prepare_generating_doc.py +++ b/salome_adm/prepare_generating_doc.py @@ -45,7 +45,7 @@ def main(input_file, output_file = None): # open input file try: infile = open(input_file, 'rb') - except: + except Exception: sys.exit("File %s is not found" % input_file) pass @@ -54,7 +54,7 @@ def main(input_file, output_file = None): # open output file try: outfile = open(output_file, 'wb') - except: + except Exception: sys.exit("File %s cannot be opened for write" % output_file) pass diff --git a/src/Container/SALOME_Container.py b/src/Container/SALOME_Container.py index 7b0c76fd9..13c63fb8b 100644 --- a/src/Container/SALOME_Container.py +++ b/src/Container/SALOME_Container.py @@ -87,10 +87,10 @@ class SALOME_Container_i: ret=ret+traceback.format_exc(10) except ImportError as ee: ret="ImplementationNotFound" - except: + except Exception: if verbose():print("error when calling find_module") ret="ImplementationNotFound" - except: + except Exception: ret="Component "+componentName+": Python implementation found but it can't be loaded\n" ret=ret+traceback.format_exc(10) if verbose(): @@ -117,7 +117,7 @@ class SALOME_Container_i: MESSAGE( "SALOME_Container_i::create_component_instance : OK") comp_o = comp_i._this() comp_iors = self._orb.object_to_string(comp_o) - except: + except Exception: ret=traceback.format_exc(10) traceback.print_exc() MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK") @@ -131,7 +131,7 @@ class SALOME_Container_i: comp_o = self._poa.id_to_reference(id_o) comp_iors = self._orb.object_to_string(comp_o) return 0,comp_iors - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) return 1,"".join(l) @@ -143,7 +143,7 @@ class SALOME_Container_i: comp_o = self._poa.id_to_reference(id_o) comp_iors = self._orb.object_to_string(comp_o) return 0,comp_iors - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) return 1,"".join(l) diff --git a/src/Container/SALOME_ContainerPy.py b/src/Container/SALOME_ContainerPy.py index cbe887ff9..7b2bb522f 100755 --- a/src/Container/SALOME_ContainerPy.py +++ b/src/Container/SALOME_ContainerPy.py @@ -113,7 +113,7 @@ class SALOME_ContainerPy_Gen_i(Engines__POA.Container): print(reason) pass pass - except: + except Exception: import traceback print("cannot import %s" % componentName) traceback.print_exc() @@ -153,7 +153,7 @@ class SALOME_ContainerPy_Gen_i(Engines__POA.Container): MESSAGE( "SALOME_Container_i::create_component_instance : OK") comp_o = comp_i._this() self._listInstances_map[instanceName] = comp_i - except: + except Exception: import traceback traceback.print_exc() MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK") diff --git a/src/Container/SALOME_PyNode.py b/src/Container/SALOME_PyNode.py index a4281285b..49ed9e5e2 100644 --- a/src/Container/SALOME_PyNode.py +++ b/src/Container/SALOME_PyNode.py @@ -87,7 +87,7 @@ class PyNode_i (Engines__POA.PyNode,Generic): try: ccode=compile(code,self.nodeName,'exec') exec(ccode, self.context) - except: + except Exception: raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0)) def execute(self,funcName,argsin): @@ -98,7 +98,7 @@ class PyNode_i (Engines__POA.PyNode,Generic): argsout=func(*argsin,**kws) argsout=pickle.dumps(argsout,-1) return argsout - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyNode: %s, function: %s" % (self.nodeName,funcName),0)) @@ -134,14 +134,14 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): try: ccode=compile(code,self.nodeName,'exec') exec(ccode, self.context) - except: + except Exception: raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0)) def assignNewCompiledCode(self,codeStr): try: self.code=codeStr self.ccode=compile(codeStr,self.nodeName,'exec') - except: + except Exception: raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode.assignNewCompiledCode (%s) : code to be executed \"%s\"" %(self.nodeName,codeStr),0)) def execute(self,outargsname,argsin): @@ -157,7 +157,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): argsout.append(self.context[arg]) argsout=pickle.dumps(tuple(argsout),-1) return argsout - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s, outargsname: %s" % (self.nodeName,outargsname),0)) @@ -168,7 +168,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): try: _,kws=pickle.loads(argsin) self.context.update(kws) - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:First %s" % (self.nodeName),0)) @@ -184,7 +184,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): argsout.append(self.context[arg]) argsout=pickle.dumps(tuple(argsout),-1) return argsout - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:Second %s, outargsname: %s" % (self.nodeName,outargsname),0)) @@ -192,7 +192,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): def getValueOfVarInContext(self,varName): try: return pickle.dumps(self.context[varName],-1) - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0)) @@ -201,7 +201,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): def assignVarInContext(self, varName, value): try: self.context[varName][0] = pickle.loads(value) - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0)) @@ -210,7 +210,7 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic): def callMethodOnVarInContext(self, varName, methodName, args): try: return pickle.dumps( getattr(self.context[varName][0],methodName)(*pickle.loads(args)),-1 ) - except: + except Exception: exc_typ,exc_val,exc_fr=sys.exc_info() l=traceback.format_exception(exc_typ,exc_val,exc_fr) raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0)) diff --git a/src/KERNEL_PY/__init__.py b/src/KERNEL_PY/__init__.py index 5952cc924..d92792124 100644 --- a/src/KERNEL_PY/__init__.py +++ b/src/KERNEL_PY/__init__.py @@ -136,7 +136,7 @@ if not flags: # dl module can be unavailable import dl flags = dl.RTLD_NOW | dl.RTLD_GLOBAL - except: + except Exception: pass pass if not flags: @@ -144,7 +144,7 @@ if not flags: # DLFCN module can be unavailable import DLFCN flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL - except: + except Exception: pass pass if not flags: @@ -152,7 +152,7 @@ if not flags: # ctypes module can be unavailable import ctypes flags = ctypes.RTLD_GLOBAL - except: + except Exception: pass pass @@ -255,7 +255,7 @@ def salome_close(): try: # study can be clear either from GUI or directly with salome.myStudy.Clear() myStudy.Clear() - except: + except Exception: pass salome_initial=True salome_iapp_close() @@ -300,7 +300,7 @@ def salome_shutdown_containers(): for cont,(root,cont_name) in li: try: cont.Shutdown() - except: + except Exception: pass ref_in_ns = "/".join(root+[cont_name]) naming_service.Destroy_Name(ref_in_ns) diff --git a/src/KERNEL_PY/kernel/enumerate.py b/src/KERNEL_PY/kernel/enumerate.py index 0f3f18f1d..8c43b40e2 100644 --- a/src/KERNEL_PY/kernel/enumerate.py +++ b/src/KERNEL_PY/kernel/enumerate.py @@ -19,7 +19,7 @@ # ## \defgroup enumerate enumerate -# \{ +# \{ # \details Emulates a C-like enum for python # \} @@ -30,13 +30,13 @@ __date__ = "$1 avr. 2010 09:08:02$" # of strings to be used as the enum symbolic keys. The enum values are automatically # generated as sequencing integer starting at the specified offset value. # \ingroup enumerate -class Enumerate(object): +class Enumerate: """ This class emulates a C-like enum for python. It is initialized with a list of strings to be used as the enum symbolic keys. The enum values are automatically generated as sequencing integer starting at the specified offset value. """ - + ## Canonical constructor. # \param keys a list of string to be used as the enum symbolic keys. The enum values # are automatically generated as a sequence of integers starting at the specified diff --git a/src/KERNEL_PY/kernel/studyedit.py b/src/KERNEL_PY/kernel/studyedit.py index c41a2e8fa..091dcf2e0 100644 --- a/src/KERNEL_PY/kernel/studyedit.py +++ b/src/KERNEL_PY/kernel/studyedit.py @@ -461,7 +461,7 @@ class StudyEditor: else: self.builder.RemoveObject(item) ok = True - except: + except Exception: ok = False return ok diff --git a/src/KERNEL_PY/kernel/testdata.py b/src/KERNEL_PY/kernel/testdata.py index 31022ce48..b469dcb55 100644 --- a/src/KERNEL_PY/kernel/testdata.py +++ b/src/KERNEL_PY/kernel/testdata.py @@ -145,7 +145,7 @@ def TEST_serialize(): try: res_testdata.setName("An other name") print(res_testdata.getName()) - except: + except Exception: print(e) return False return True diff --git a/src/KERNEL_PY/salome_iapp.py b/src/KERNEL_PY/salome_iapp.py index 62783e60e..63fa30b10 100644 --- a/src/KERNEL_PY/salome_iapp.py +++ b/src/KERNEL_PY/salome_iapp.py @@ -68,7 +68,7 @@ def hasDesktop(): salome_iapp_initial = 1 -class SalomeOutsideGUI(object): +class SalomeOutsideGUI: """ Provides a replacement for class SalomeGUI outside GUI process. Do almost nothing @@ -197,5 +197,5 @@ def register_module_in_study(name, syncCall=True): session_server.emitMessage(message) else: session_server.emitMessageOneWay(message) - except: + except Exception: pass diff --git a/src/KERNEL_PY/salome_notebook.py b/src/KERNEL_PY/salome_notebook.py index 2721cf0a4..6920f0ba4 100644 --- a/src/KERNEL_PY/salome_notebook.py +++ b/src/KERNEL_PY/salome_notebook.py @@ -29,76 +29,76 @@ Module salome_notebook gives access to Salome Notebook. import salome -class PseudoStudyForNoteBook(object): - +class PseudoStudyForNoteBook: + def __init__(self, **kwargs): self.kwargs = kwargs pass - + def GetVariableNames(self): return list(self.kwargs.keys()) - + def IsVariable(self, variableName): return variableName in self.kwargs - + def IsReal(self, variableName): val = self.kwargs[variableName] try: float(val) return True - except: + except Exception: pass return False - + IsInteger = IsReal IsBoolean = IsReal - + def IsString(self, variableName): return not self.IsReal(variableName) - + def GetString(self, variableName): return self.kwargs[variableName] - + def GetReal(self, variableName): return float(self.kwargs[variableName]) - + GetInteger = GetReal GetBoolean = GetReal - + pass class NoteBook: - - def __init__(self, theIsEnablePublish = True): + + def __init__(self, theIsEnablePublish=True): if theIsEnablePublish: self.myStudy = salome.myStudy else: self.myStudy = PseudoStudyForNoteBook() - + def set(self, variableName, variable): """ - Create (or modify) variable with name "variableName" + Create (or modify) variable with name "variableName" and value equal "theValue". """ if isinstance(variable, float): self.myStudy.SetReal(variableName, variable) - + elif isinstance(variable, int): self.myStudy.SetInteger(variableName, variable) - + elif isinstance(variable, bool): self.myStudy.SetBoolean(variableName, variable) - + elif isinstance(variable, str): self.myStudy.SetString(variableName, variable) - + def get(self, variableName): """ Return value of the variable with name "variableName". """ aResult = None if self.myStudy.IsVariable(variableName): - + if self.myStudy.IsReal(variableName): aResult = self.myStudy.GetReal(variableName) @@ -111,18 +111,18 @@ class NoteBook: elif self.myStudy.IsString(variableName): aResult = self.myStudy.GetString(variableName) aResult_orig = aResult - l = self.myStudy.GetVariableNames() - l.remove(variableName) + list_of_variables = self.myStudy.GetVariableNames() + list_of_variables.remove(variableName) # -- # To avoid the smallest strings to be replaced first, # the list is sorted by decreasing lengths # -- - l.sort(key=str.__len__) - l.reverse() - for name in l: + list_of_variables.sort(key=str.__len__) + list_of_variables.reverse() + for name in list_of_variables: if aResult.find(name) >= 0: val = self.get(name) - aResult = aResult.replace(name, "%s"%(val)) + aResult = aResult.replace(name, "%s" % (val)) pass pass try: @@ -131,18 +131,18 @@ class NoteBook: msg = str(e) msg += "\n" msg += "A problem occurs while parsing " - msg += "the variable %s "%(variableName.__repr__()) - msg += "with value %s ..."%(aResult_orig.__repr__()) + msg += "the variable %s " % (variableName.__repr__()) + msg += "with value %s ..." % (aResult_orig.__repr__()) msg += "\n" msg += "Please, check your notebook !" raise Exception(msg) pass - + return aResult - - def isVariable(self, variableName): + + def isVariable(self, variableName): """ - Return true if variable with name "variableName" + Return true if variable with name "variableName" exists in the study, otherwise return false. """ return self.myStudy.IsVariable(variableName) @@ -152,30 +152,32 @@ class NoteBook: value = float(typ(value)) self.myStudy.SetStringAsDouble(variableName, value) return - + def setAsReal(self, variableName): self.setAs(variableName, float) return - + def setAsInteger(self, variableName): self.setAs(variableName, int) return - + def setAsBool(self, variableName): self.setAs(variableName, bool) return - + def check(self): for variableName in self.myStudy.GetVariableNames(): self.get(variableName) pass return - + pass + def checkThisNoteBook(**kwargs): - note_book = NoteBook( False ) + note_book = NoteBook(False) note_book.check() return + notebook = NoteBook() diff --git a/src/KERNEL_PY/salome_version.py b/src/KERNEL_PY/salome_version.py index a1d5c1cc0..7ddfde2d7 100644 --- a/src/KERNEL_PY/salome_version.py +++ b/src/KERNEL_PY/salome_version.py @@ -70,7 +70,7 @@ def getVersion( mod = "KERNEL", full = False ): elif "version" in key.lower() or mod in key: _salome_versions[ mod ][ 0 ] = val pass - except: + except Exception: pass v = _salome_versions[ mod ][ 0 ] if full and v is not None: @@ -87,7 +87,7 @@ def getVersionMajor( mod = "KERNEL" ): ver = getVersion( mod ) try: return ver.split( "." )[ 0 ] - except: + except Exception: pass return None @@ -101,7 +101,7 @@ def getVersionMinor( mod = "KERNEL" ): ver = getVersion( mod ) try: return ver.split( "." )[ 1 ] - except: + except Exception: pass return None @@ -115,7 +115,7 @@ def getVersionRelease( mod = "KERNEL" ): ver = getVersion( mod ) try: return ver.split( "." )[ 2 ] - except: + except Exception: pass return None @@ -128,17 +128,17 @@ def getVersions( mod = "KERNEL" ): """ try: major = int( getVersionMajor( mod ) ) - except: + except Exception: major = 0 pass try: minor = int( getVersionMinor( mod ) ) - except: + except Exception: minor = 0 pass try: rel = int( getVersionRelease( mod ) ) - except: + except Exception: rel = 0 pass return [ major, minor, rel ] diff --git a/src/Launcher/launcher_proxy.py b/src/Launcher/launcher_proxy.py index e4f8fd6a3..d757f55ed 100755 --- a/src/Launcher/launcher_proxy.py +++ b/src/Launcher/launcher_proxy.py @@ -26,7 +26,7 @@ import time JOB_FILE_NAME = "jobDump.xml" -class Job(object): +class Job: """ This class makes an easier access to SalomeLauncher. It adds an automatic save of the job's parameters after the launch. The save @@ -62,7 +62,7 @@ class Job(object): with open(job_file_path, "r") as f: job_string = f.read() myjob.job_id = launcher.restoreJob(job_string) - except: + except Exception: myjob = None return myjob diff --git a/src/Logger/Test/TestKiller.py b/src/Logger/Test/TestKiller.py index 8118098cd..4246d3ff0 100644 --- a/src/Logger/Test/TestKiller.py +++ b/src/Logger/Test/TestKiller.py @@ -37,7 +37,7 @@ def closeSalome(): from PortManager import releasePort print("### release current port:", port) releasePort(port) - except: + except Exception: pass @@ -54,7 +54,7 @@ def killNamingService(): try: pid=output_com.split()[0] os.kill(int(pid),signal.SIGKILL) - except: + except Exception: print("killNamingService failed.") @@ -68,7 +68,7 @@ def killProcess(process_id): print("stop process %s : %s"% (pid, cmd[0])) try: os.kill(int(pid),signal.SIGKILL) - except: + except Exception: print(" ---- process %s : %s inexistant"% (pid, cmd[0])) pass del process_id[pid] diff --git a/src/NamingService/SALOME_NamingServicePy.py b/src/NamingService/SALOME_NamingServicePy.py index dfabbf11b..00360abd0 100644 --- a/src/NamingService/SALOME_NamingServicePy.py +++ b/src/NamingService/SALOME_NamingServicePy.py @@ -40,7 +40,7 @@ from string import * from SALOME_utilities import * #============================================================================= -class SALOME_NamingServicePy_i(object): +class SALOME_NamingServicePy_i: """ A class to manage SALOME naming service from python code """ diff --git a/src/SALOMEDS/SALOME_DriverPy.py b/src/SALOMEDS/SALOME_DriverPy.py index c135daf08..7cfb353bd 100644 --- a/src/SALOMEDS/SALOME_DriverPy.py +++ b/src/SALOMEDS/SALOME_DriverPy.py @@ -49,7 +49,7 @@ class SALOME_DriverPy_i(SALOMEDS__POA.Driver): def Version(self): try: return self.getVersion() - except: + except Exception: return '' def Save(self, theComponent, theURL, isMultiFile): diff --git a/src/SALOMESDS/SALOMEGlobalVarHelper.py b/src/SALOMESDS/SALOMEGlobalVarHelper.py index bb2228c67..533062855 100644 --- a/src/SALOMESDS/SALOMEGlobalVarHelper.py +++ b/src/SALOMESDS/SALOMEGlobalVarHelper.py @@ -23,7 +23,7 @@ import SALOME import pickle -class List(object): +class List: def __init__(self,varPtr,isTemporaryVar=False): assert(isinstance(varPtr,SALOME._objref_StringDataServer)) self._var_ptr=varPtr @@ -67,7 +67,7 @@ class List(object): pass -class Tuple(object): +class Tuple: def __init__(self,varPtr,isTemporaryVar=False): assert(isinstance(varPtr,SALOME._objref_StringDataServer)) self._var_ptr=varPtr @@ -106,9 +106,9 @@ class Tuple(object): return (tuple,(self.local_copy(),)) pass - -class Int(object): + +class Int: def __init__(self,varPtr,isTemporaryVar=False): assert(isinstance(varPtr,SALOME._objref_StringDataServer)) self._var_ptr=varPtr @@ -148,7 +148,7 @@ class Int(object): pass -class Dict(object): +class Dict: def __init__(self,varPtr,isTemporaryVar=False): assert(isinstance(varPtr,SALOME._objref_StringDataServer)) self._var_ptr=varPtr diff --git a/src/SALOMESDS/SalomeSDSClt.py b/src/SALOMESDS/SalomeSDSClt.py index d1f09c1ac..07c03f742 100644 --- a/src/SALOMESDS/SalomeSDSClt.py +++ b/src/SALOMESDS/SalomeSDSClt.py @@ -23,7 +23,7 @@ import SALOME import pickle import SALOMEWrappedStdType -class InvokatorStyle(object): +class InvokatorStyle: def __init__(self,varPtr): self._var_ptr=varPtr def ptr(self): diff --git a/src/Utils/Utils_Identity.py b/src/Utils/Utils_Identity.py index a3b119c79..ae7713011 100644 --- a/src/Utils/Utils_Identity.py +++ b/src/Utils/Utils_Identity.py @@ -82,7 +82,7 @@ try: versnb = string.strip(string.split(s, ":")[1]) dirname=".salome_"+versnb file.close() -except: +except Exception: versnb = "" dirname=".salome" -- 2.39.2