We are in python3: no more need to inherite classes from object.
try:
import cPickle as pickle #@UnusedImport
-except:
+except ImportError:
import pickle #@Reimport
__PORT_MIN_NUMBER = 2810
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
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
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
try:
with open(filedict, 'rb') as fpid:
process_ids=pickle.load(fpid)
- except:
+ except Exception:
process_ids=[]
pass
# kill processes
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
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
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", []):
# 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
with open(port_log) as f:
salome_instance.port = int(f.readline())
os.remove(port_log)
- except:
+ except Exception:
pass
return salome_instance
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()
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()
match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', v )
if match :
return match.group( 1 )
- except:
+ except Exception:
pass
return ''
else:
if isinstance( strloc, bytes):
strloc = strloc.decode().strip()
- except:
+ except Exception:
pass
return strloc
pass
pass
pass
- except:
+ except Exception:
if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname)
pass
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
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
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 = ""
upath = os.path.join(upath, "omniNames_%s"%(aPort))
try:
os.mkdir(upath)
- except:
+ except Exception:
# print("Can't create " + upath)
pass
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")
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)
my_port=str(args['port'])
try:
killMyPort(my_port)
- except:
+ except Exception:
print("problem in killLocalPort()")
pass
pass
my_port=port
try:
killMyPort(my_port)
- except:
+ except Exception:
print("problem in LocalPortKill(), killMyPort(%s)"%port)
pass
pass
try:
if 'interp' in args:
nbaddi = args['interp']
- except:
+ except Exception:
import traceback
traceback.print_exc()
print("-------------------------------------------------------------")
clt=None
try:
clt = startSalome(args, modules_list, modules_root_dir)
- except:
+ except Exception:
import traceback
traceback.print_exc()
print()
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
status = session.GetStatSession()
gui_detected = status.activeGUI
session_pid = session.getPID()
- except:
+ except Exception:
pass
if gui_detected:
break
try:
status = session.GetStatSession()
assert status.activeGUI
- except:
+ except Exception:
break
from time import sleep
sleep(dt)
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"
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
if proc.returncode != 0:
any_error = True
error_code = proc.returncode
- except:
+ except Exception:
any_error = True
pass
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
#
path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome", "appliskel"))
add_path(path, "PYTHONPATH")
- except:
+ except Exception:
pass
command, options = self.__parseArguments(args)
versions[software.upper()] = version
if len(software) > max_len:
max_len = len(software)
- except:
+ except Exception:
pass
pass
pass
break
pass
fn.close()
- except:
+ except Exception:
pass
if not ispython and script_extension == ".py":
currentKey = "@PYTHONBIN@ "+currentScript
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
os.symlink(omniorb_config, last_running_config)
pass
pass
- except:
+ except Exception:
pass
#
#
try:
os.kill(childpid,0)
return childpid
- except:
+ except Exception:
return None
#first child
mod=__import__(module.lower()+"_setenv")
mod.set_env(args)
pass
- except:
+ except Exception:
pass
pass
pass
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
# open input file
try:
infile = open(input_file, 'rb')
- except:
+ except Exception:
sys.exit("File %s is not found" % input_file)
pass
# open output file
try:
outfile = open(output_file, 'wb')
- except:
+ except Exception:
sys.exit("File %s cannot be opened for write" % output_file)
pass
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():
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")
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)
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)
print(reason)
pass
pass
- except:
+ except Exception:
import traceback
print("cannot import %s" % componentName)
traceback.print_exc()
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")
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):
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))
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):
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))
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))
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))
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))
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))
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))
# dl module can be unavailable
import dl
flags = dl.RTLD_NOW | dl.RTLD_GLOBAL
- except:
+ except Exception:
pass
pass
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:
# ctypes module can be unavailable
import ctypes
flags = ctypes.RTLD_GLOBAL
- except:
+ except Exception:
pass
pass
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()
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)
#
## \defgroup enumerate enumerate
-# \{
+# \{
# \details Emulates a C-like enum for python
# \}
# 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
else:
self.builder.RemoveObject(item)
ok = True
- except:
+ except Exception:
ok = False
return ok
try:
res_testdata.setName("An other name")
print(res_testdata.getName())
- except:
+ except Exception:
print(e)
return False
return True
salome_iapp_initial = 1
-class SalomeOutsideGUI(object):
+class SalomeOutsideGUI:
"""
Provides a replacement for class SalomeGUI outside GUI process.
Do almost nothing
session_server.emitMessage(message)
else:
session_server.emitMessageOneWay(message)
- except:
+ except Exception:
pass
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)
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:
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)
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()
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:
ver = getVersion( mod )
try:
return ver.split( "." )[ 0 ]
- except:
+ except Exception:
pass
return None
ver = getVersion( mod )
try:
return ver.split( "." )[ 1 ]
- except:
+ except Exception:
pass
return None
ver = getVersion( mod )
try:
return ver.split( "." )[ 2 ]
- except:
+ except Exception:
pass
return None
"""
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 ]
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
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
from PortManager import releasePort
print("### release current port:", port)
releasePort(port)
- except:
+ except Exception:
pass
try:
pid=output_com.split()[0]
os.kill(int(pid),signal.SIGKILL)
- except:
+ except Exception:
print("killNamingService failed.")
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]
from SALOME_utilities import *
#=============================================================================
-class SALOME_NamingServicePy_i(object):
+class SALOME_NamingServicePy_i:
"""
A class to manage SALOME naming service from python code
"""
def Version(self):
try:
return self.getVersion()
- except:
+ except Exception:
return ''
def Save(self, theComponent, theURL, isMultiFile):
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
pass
-class Tuple(object):
+class Tuple:
def __init__(self,varPtr,isTemporaryVar=False):
assert(isinstance(varPtr,SALOME._objref_StringDataServer))
self._var_ptr=varPtr
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
pass
-class Dict(object):
+class Dict:
def __init__(self,varPtr,isTemporaryVar=False):
assert(isinstance(varPtr,SALOME._objref_StringDataServer))
self._var_ptr=varPtr
import pickle
import SALOMEWrappedStdType
-class InvokatorStyle(object):
+class InvokatorStyle:
def __init__(self,varPtr):
self._var_ptr=varPtr
def ptr(self):
versnb = string.strip(string.split(s, ":")[1])
dirname=".salome_"+versnb
file.close()
-except:
+except Exception:
versnb = ""
dirname=".salome"