From a4874256219c549a9b1ff740d549391c4bf2f25f Mon Sep 17 00:00:00 2001 From: Gilles DAVID Date: Fri, 28 May 2021 11:54:44 +0200 Subject: [PATCH] venv directory is configured in config_appli.xml file Update appli_clean command Getting rid of old stuff getUserName now uses the standard getpass module Do not use bare "except:" instruction We are in python3: no more need to inherite classes from object. cPickle does not exist anymore in python 3 Detect psutil Python module --- CMakeLists.txt | 1 + bin/PortManager.py | 7 +- bin/addToKillList.py | 8 +- bin/appli_clean.sh | 2 +- bin/appli_gen.py | 47 ++++++++++- bin/appliskel/getAppliPath.py | 30 +------ .../salome_tester/salome_instance.py | 4 +- .../salome_tester/salome_test_driver.py | 4 +- .../salome_tester/salome_test_driver_gui.py | 4 +- bin/launchConfigureParser.py | 12 +-- bin/nameserver.py | 4 +- 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 | 10 ++- 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 +- 39 files changed, 191 insertions(+), 168 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e7b238f57..6d3fce22d 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -83,6 +83,7 @@ ENDIF() FIND_PACKAGE(SalomePythonInterp REQUIRED) FIND_PACKAGE(SalomePythonLibs REQUIRED) FIND_PACKAGE(SalomeNumPySciPy) +FIND_PACKAGE(SalomePsutil REQUIRED) FIND_PACKAGE(SalomePThread REQUIRED) FIND_PACKAGE(SalomeSWIG REQUIRED) FIND_PACKAGE(SalomeLibXml2 REQUIRED) diff --git a/bin/PortManager.py b/bin/PortManager.py index 539a35942..a07bd40d4 100644 --- a/bin/PortManager.py +++ b/bin/PortManager.py @@ -27,10 +27,7 @@ import psutil from socket import AF_INET, SOCK_STREAM -try: - import cPickle as pickle #@UnusedImport -except: - import pickle #@Reimport +import pickle __PORT_MIN_NUMBER = 2810 __PORT_MAX_NUMBER = 2910 @@ -126,7 +123,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_clean.sh b/bin/appli_clean.sh index d97717862..927c17ddb 100755 --- a/bin/appli_clean.sh +++ b/bin/appli_clean.sh @@ -23,7 +23,7 @@ #clean appli -DELCOM="rm -rf bin lib share doc idl env.d envd USERS getAppliPath.py runRemote.sh SalomeApp.xml update_catalogs.py kill_remote_containers.py salome *.pyc *~ .bashrc" +DELCOM="rm -rf bin lib share doc idl env.d envd venv USERS getAppliPath.py runRemote.sh SalomeApp.xml update_catalogs.py kill_remote_containers.py salome .salome_run salome_common.py salome_mesa __pycache__ *.pyc *~ .bashrc" DOIT="false" if [ $# -gt 0 ] diff --git a/bin/appli_gen.py b/bin/appli_gen.py index 63ef70436..b01e789b0 100755 --- a/bin/appli_gen.py +++ b/bin/appli_gen.py @@ -43,6 +43,7 @@ import subprocess appli_tag = "application" prereq_tag = "prerequisites" context_tag = "context" +venv_directory_tag = "venv_directory" sha1_collect_tag = "sha1_collections" system_conf_tag = "system_conf" modules_tag = "modules" @@ -99,6 +100,10 @@ class xml_parser: if self.space == [appli_tag, context_tag] and path_att in attrs.getNames(): self.config["context_path"] = attrs.getValue( path_att ) pass + # --- if we are analyzing "venv_directory" element then store its "path" attribute + if self.space == [appli_tag, venv_directory_tag] and path_att in attrs.getNames(): + self.config["venv_directory_path"] = attrs.getValue( path_att ) + pass # --- if we are analyzing "sha1_collection" element then store its "path" attribute if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames(): self.config["sha1_collect_path"] = attrs.getValue( path_att ) @@ -205,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 @@ -218,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", []): @@ -289,6 +294,10 @@ def install(prefix, config_file, verbose=0): # Creation of env.d directory virtual_salome.mkdir(os.path.join(home_dir,'env.d')) + venv_directory_path = _config.get('venv_directory_path') + if venv_directory_path and os.path.isdir(venv_directory_path): + virtual_salome.symlink(venv_directory_path, os.path.join(home_dir, "venv")) + # Get the env modules which will be loaded # In the same way as: module load [MODULE_LIST] env_modules = _config.get('env_modules', []) @@ -352,6 +361,19 @@ def install(prefix, config_file, verbose=0): cmd='source %s && python3 -c "import sys ; sys.stdout.write(\\"{}.{}\\".format(sys.version_info.major,sys.version_info.minor))"' %(_config["prereq_path"]) versionPython=subprocess.check_output(['/bin/bash', '-l' ,'-c',cmd]).decode("utf-8") + venv_directory_path = None + if "venv_directory_path" in _config: + venv_directory_path = _config["venv_directory_path"] + venv_bin_directory_path = os.path.join(venv_directory_path, 'bin') + venv_pip_executable = os.path.join(venv_bin_directory_path, 'pip') + venv_python_executable = os.path.join(venv_bin_directory_path, 'python') + if os.path.isdir(venv_directory_path) and os.path.isfile(venv_pip_executable): + requirement_file = os.path.join(home_dir, 'requirements.txt') + with open(requirement_file, 'w') as fd: + subprocess.call([venv_python_executable, '-m', 'pip', 'freeze'], stdout=fd) + else: + venv_directory_path = None + with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f: for module in _config.get("modules", []): command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n' @@ -386,6 +408,16 @@ export LD_LIBRARY_PATH=${HOME}/${APPLI}/lib/salome:$LD_LIBRARY_PATH # Create environment for Meshers command = "export SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin:GHS3DPRLPlugin\nexport SALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n" f.write(command) + # Create environment for virtual env + if venv_directory_path: + command = """# SALOME venv Configuration +export SALOME_VENV_DIRECTORY=%s +export PATH=${HOME}/${APPLI}/venv/bin:$PATH +export LD_LIBRARY_PATH=${HOME}/${APPLI}/venv/lib:$LD_LIBRARY_PATH +export PYTHONPATH=${HOME}/${APPLI}/venv/lib/python%s/site-packages +""" % (venv_directory_path, versionPython) + f.write(command) + pass # Create configuration file: configSalome.cfg with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f: @@ -421,7 +453,16 @@ ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/lib/salome # Create environment for Meshers command = "SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin:GHS3DPRLPlugin\nSALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n" f.write(command) - + # Create environment for virtual env + if venv_directory_path: + command = """[SALOME venv Configuration] +SALOME_VENV_DIRECTORY: %s +ADD_TO_PATH: ${HOME}/${APPLI}/venv/bin +ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/venv/lib +ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/venv/lib/python%s/site-packages +""" % (venv_directory_path, versionPython) + f.write(command) + pass # Create environment file: configGUI.sh dirs_ress_icon = [] diff --git a/bin/appliskel/getAppliPath.py b/bin/appliskel/getAppliPath.py index 858a670af..91479e551 100755 --- a/bin/appliskel/getAppliPath.py +++ b/bin/appliskel/getAppliPath.py @@ -23,30 +23,9 @@ # import os -import sys - -###### -# Warning: relpath might be replaced by equivalent os.relpath introduced in -# Python 2.6 (Calibre 7). -# It is still here to ensure compatibility with Calibre 6 (Python 2.5) -def relpath(target, base): - """ Find relative path from base to target - if target== "/local/chris/appli" and base== "/local/chris" the result is appli - if target== /tmp/appli and base /local/chris the result is ../../tmp/appli - """ - target=target.split(os.path.sep) - base=base.split(os.path.sep) - for i in range(len(base)): - if base[i] != target[i]: - i=i-1 - #not in base - break - p=['..']*(len(base)-i-1)+target[i+1:] - if p == []: - return '.' - return os.path.join( *p ) # + def get_appli_path(filePath=None): if filePath is None: filePath = os.path.realpath(os.path.dirname(__file__)) @@ -56,10 +35,7 @@ def get_appli_path(filePath=None): return applipath # + if __name__ == "__main__": - if sys.hexversion < 0x02060000: # Python older than 2.6.0 - applipath = relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.path.expanduser("~"))) - else: - applipath = get_appli_path() - print(applipath) + print(get_appli_path()) # 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/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 0b8e41c65..77d04f802 100644 --- a/bin/nameserver.py +++ b/bin/nameserver.py @@ -63,7 +63,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 @@ -71,7 +71,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 32543205e..be7fc03d4 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) @@ -503,7 +503,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 114793af0..346db515a 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -116,8 +116,14 @@ def getUserName(): :return user name """ - return os.getenv('USERNAME', 'unknown') if sys.platform == 'win32' \ - else os.getenv('USER', os.getenv('LOGNAME', 'unknown')) + if sys.platform == 'win32': + username = os.getenv('USERNAME') + else: + username = os.getenv('USER', os.getenv('LOGNAME')) + if username is None: + import getpass + username = getpass.getuser() + return username # --- 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 d5ee4ec14..0dacb86b7 100755 --- a/src/Container/SALOME_ContainerPy.py +++ b/src/Container/SALOME_ContainerPy.py @@ -117,7 +117,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() @@ -157,7 +157,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 ad8f52425..2aa01975b 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 @@ -341,7 +341,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() @@ -392,7 +392,7 @@ def salome_shutdown_containers_with_session(): 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 d7c7dea6c..00c58fbf0 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 @@ -202,5 +202,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