From a4f1d4d818127b769abf1887ef011eb85da7cbd4 Mon Sep 17 00:00:00 2001 From: Gilles DAVID Date: Fri, 21 Nov 2014 19:18:12 +0100 Subject: [PATCH] Some Python refactoring and use argparse instead of optparse --- bin/NSparam.py | 6 +- bin/ORBConfigFile.py | 9 +- bin/PortManager.py | 6 +- bin/addToKillList.py | 4 +- bin/appli_gen.py | 181 +++++++++++++++++------------------ bin/envSalome.py | 2 +- bin/killSalomeWithPort.py | 32 ++++--- bin/launchConfigureParser.py | 74 +++++++------- bin/nameserver.py | 55 ++++++----- bin/orbmodule.py | 132 ++++++++++++------------- bin/parseConfigFile.py | 4 +- bin/runConsole.py | 2 +- bin/salome_utils.py | 20 +--- 13 files changed, 255 insertions(+), 272 deletions(-) diff --git a/bin/NSparam.py b/bin/NSparam.py index cde5c7cd3..f1c2dd35c 100755 --- a/bin/NSparam.py +++ b/bin/NSparam.py @@ -35,13 +35,13 @@ def getNSparams(info=""): else print 2 strings on stdout on one line: host port """ from salome_utils import getORBcfgInfo - my_version, my_host, my_port = getORBcfgInfo() + _, my_host, my_port = getORBcfgInfo() if info=='host': - os.environ['NSHOST']=my_host + os.environ['NSHOST'] = my_host return my_host pass elif info=='port': - os.environ['NSPORT']=my_port + os.environ['NSPORT'] = my_port return my_port pass else: diff --git a/bin/ORBConfigFile.py b/bin/ORBConfigFile.py index 02bdf59a4..2c693445d 100644 --- a/bin/ORBConfigFile.py +++ b/bin/ORBConfigFile.py @@ -40,7 +40,7 @@ def writeORBConfigFile(path, host, port, kwargs={}): from omniORB import CORBA prefix = "" if CORBA.ORB_ID == "omniORB4" else "ORB" - GIOP_MaxMsgSize=2097152000 # 2 GBytes + GIOP_MaxMsgSize = 2097152000 # 2 GBytes orbdata = [] orbdata.append("%sInitRef = NameService=corbaname::%s:%s"%(prefix,host,port)) @@ -49,16 +49,15 @@ def writeORBConfigFile(path, host, port, kwargs={}): orbdata.append("%smaxGIOPConnectionPerServer = 50 # to allow containers parallel launch"%(prefix)) orbdata.append("") - f = open(omniorb_config, "w") - f.write("\n".join(orbdata)) - f.close() + with open(omniorb_config, "w") as f: + f.write("\n".join(orbdata)) return [ omniorb_config, GIOP_MaxMsgSize ] # ----------------------------------------------------------------------------- if __name__ == "__main__": - import sys, getopt + import sys path = sys.argv[1] host = sys.argv[2] diff --git a/bin/PortManager.py b/bin/PortManager.py index 0d01ce950..465ac8784 100644 --- a/bin/PortManager.py +++ b/bin/PortManager.py @@ -25,9 +25,9 @@ import os import sys try: - import cPickle as pickle + import cPickle as pickle #@UnusedImport except: - import pickle + import pickle #@Reimport import logging def createLogger(): @@ -88,7 +88,7 @@ def __isNetworkConnectionActiveOnPort(port): # netstat options -l and -t are unavailable # grep command is unavailable from subprocess import Popen, PIPE - (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate() + stdout, _ = Popen(['netstat','-an'], stdout=PIPE).communicate() import StringIO buf = StringIO.StringIO(stdout) ports = buf.readlines() diff --git a/bin/addToKillList.py b/bin/addToKillList.py index 7d688aca2..24ca6783f 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -22,7 +22,7 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -import os, sys, pickle, string, signal +import os, sys, pickle, signal from launchConfigureParser import verbose ########## adds to the kill list of SALOME one more process ########## @@ -60,7 +60,7 @@ def addToKillList(command_pid, command, port=None): # check if PID is already in dictionary already_in=False for process_id in process_ids: - for pid, cmd in process_id.items(): + for pid in process_id.keys(): if int(pid) == int(command_pid): already_in=True break diff --git a/bin/appli_gen.py b/bin/appli_gen.py index 199790f80..5b6ee5411 100644 --- a/bin/appli_gen.py +++ b/bin/appli_gen.py @@ -19,24 +19,25 @@ # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# See http://www.salome-platform.org or email : webmaster.salome@opencascade.com # ## \file appli_gen.py # Create a %SALOME application (virtual Salome installation) # -usage="""usage: %prog [options] +usage = """%(prog)s [options] Typical use is: - python appli_gen.py + python %(prog)s Typical use with options is: - python appli_gen.py --verbose --prefix= --config= + python %(prog)s --verbose --prefix= --config= """ -import os, glob, string, sys, re +import argparse +import os +import sys import shutil -import xml.sax -import optparse import virtual_salome +import xml.sax # --- names of tags in XML configuration file appli_tag = "application" @@ -69,13 +70,13 @@ class xml_parser: parser.parse(fileName) pass - def boolValue( self, str ): - if str in ("yes", "y", "1"): + def boolValue( self, text): + if text in ("yes", "y", "1"): return 1 - elif str in ("no", "n", "0"): + elif text in ("no", "n", "0"): return 0 else: - return str + return text pass def startElement(self, name, attrs): @@ -120,7 +121,7 @@ class xml_parser: pass def endElement(self, name): - p = self.space.pop() + self.space.pop() self.current = None pass @@ -150,20 +151,20 @@ class params: def makedirs(namedir): if os.path.exists(namedir): - dirbak=namedir+".bak" + dirbak = namedir+".bak" if os.path.exists(dirbak): shutil.rmtree(dirbak) - os.rename(namedir,dirbak) + os.rename(namedir, dirbak) os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines os.makedirs(namedir) -def install(prefix,config_file,verbose=0): - home_dir=os.path.abspath(os.path.expanduser(prefix)) - filename=os.path.abspath(os.path.expanduser(config_file)) - _config={} +def install(prefix, config_file, verbose=0): + home_dir = os.path.abspath(os.path.expanduser(prefix)) + filename = os.path.abspath(os.path.expanduser(config_file)) + _config = {} try: - p = xml_parser(filename) - _config = p.config + parser = xml_parser(filename) + _config = parser.config except xml.sax.SAXParseException, inst: print inst.getMessage() print "Configure parser: parse error in configuration file %s" % filename @@ -177,23 +178,23 @@ def install(prefix,config_file,verbose=0): pass if verbose: - for cle in _config.keys(): - print cle, _config[cle] + for cle,val in _config.items(): + print cle, val pass - for module in _config.get("modules",[]): + for module in _config.get("modules", []): if _config.has_key(module): print "--- add module ", module, _config[module] options = params() - options.verbose=verbose - options.clear=0 - options.prefix=home_dir - options.module=_config[module] + options.verbose = verbose + options.clear = 0 + options.prefix = home_dir + options.module = _config[module] virtual_salome.link_module(options) pass pass - appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel') + appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel') for fn in ('envd', 'getAppliPath.py', @@ -211,94 +212,87 @@ def install(prefix,config_file,verbose=0): pass if filename != os.path.join(home_dir,"config_appli.xml"): - command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml") - os.system(command) + shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml")) pass # Creation of env.d directory virtual_salome.mkdir(os.path.join(home_dir,'env.d')) if _config.has_key("prereq_path") and os.path.isfile(_config["prereq_path"]): - command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh') - os.system(command) + shutil.copyfile(_config["prereq_path"], + os.path.join(home_dir, 'env.d', 'envProducts.sh')) pass else: print "WARNING: prerequisite file does not exist" pass if _config.has_key("context_path") and os.path.isfile(_config["context_path"]): - command='cp -p ' + _config["context_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.cfg') - os.system(command) + shutil.copyfile(_config["context_path"], + os.path.join(home_dir, 'env.d', 'envProducts.cfg')) pass else: print "WARNING: context file does not exist" pass if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]): - command='cp -p ' + _config["system_conf_path"] + ' ' + os.path.join(home_dir,'env.d','envConfSystem.sh') - os.system(command) + shutil.copyfile(_config["system_conf_path"], + os.path.join(home_dir, 'env.d', 'envConfSystem.sh')) pass # Create environment file: configSalome.sh - f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w') - for module in _config.get("modules",[]): - command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n' - f.write(command) - pass - if _config.has_key("samples_path"): - command='export DATA_DIR=' + _config["samples_path"] +'\n' - f.write(command) - pass - if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): - command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' - f.write(command) - - f.close() + 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' + f.write(command) + pass + if _config.has_key("samples_path"): + command = 'export DATA_DIR=' + _config["samples_path"] +'\n' + f.write(command) + pass + if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): + command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' + f.write(command) # Create configuration file: configSalome.cfg - f =open(os.path.join(home_dir,'env.d','configSalome.cfg'),'w') - command = "[SALOME ROOT_DIR (modules) Configuration]\n" - f.write(command) - for module in _config.get("modules",[]): - command=module + '_ROOT_DIR=${HOME}/${APPLI}\n' + with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f: + command = "[SALOME ROOT_DIR (modules) Configuration]\n" f.write(command) - pass - if _config.has_key("samples_path"): - command='DATA_DIR=' + _config["samples_path"] +'\n' - f.write(command) - pass - if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): - command='USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' - f.write(command) - - f.close() + for module in _config.get("modules", []): + command = module + '_ROOT_DIR=${HOME}/${APPLI}\n' + f.write(command) + pass + if _config.has_key("samples_path"): + command = 'DATA_DIR=' + _config["samples_path"] +'\n' + f.write(command) + pass + if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): + command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' + f.write(command) # Create environment file: configGUI.sh - f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w') - command = """export SalomeAppConfig=${HOME}/${APPLI} + with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f: + command = """export SalomeAppConfig=${HOME}/${APPLI} export SUITRoot=${HOME}/${APPLI}/share/salome export DISABLE_FPE=1 export MMGT_REENTRANT=1 """ - f.write(command) - f.close() + f.write(command) # Create configuration file: configGUI.cfg - f =open(os.path.join(home_dir,'env.d','configGUI.cfg'),'w') - command = """[SALOME GUI Configuration] + with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f: + command = """[SALOME GUI Configuration] SalomeAppConfig=${HOME}/${APPLI} SUITRoot=${HOME}/${APPLI}/share/salome DISABLE_FPE=1 MMGT_REENTRANT=1 """ - f.write(command) - f.close() + f.write(command) #SalomeApp.xml file - f =open(os.path.join(home_dir,'SalomeApp.xml'),'w') - command=""" + with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f: + command = """
@@ -318,37 +312,38 @@ MMGT_REENTRANT=1
""" - mods=[] - #Keep all modules except KERNEL and GUI - for m in _config.get("modules",[]): - if m in ("KERNEL","GUI"):continue - mods.append(m) - f.write(command % ",".join(mods)) - f.close() + mods = [] + #Keep all modules except KERNEL and GUI + for module in _config.get("modules", []): + if module in ("KERNEL","GUI"): + continue + mods.append(module) + f.write(command % ",".join(mods)) #Add USERS directory with 777 permission to store users configuration files - users_dir=os.path.join(home_dir,'USERS') + users_dir = os.path.join(home_dir,'USERS') makedirs(users_dir) os.chmod(users_dir, 0777) def main(): - parser = optparse.OptionParser(usage=usage) + parser = argparse.ArgumentParser(usage=usage) - parser.add_option('--prefix', dest="prefix", default='.', - help="Installation directory (default .)") + parser.add_argument('--prefix', default='.', metavar="", + help="Installation directory (default %(default)s)") - parser.add_option('--config', dest="config", default='config_appli.xml', - help="XML configuration file (default config_appli.xml)") + parser.add_argument('--config', default='config_appli.xml', + metavar="", + help="XML configuration file (default %(default)s)") - parser.add_option('-v', '--verbose', action='count', dest='verbose', + parser.add_argument('-v', '--verbose', action='count', default=0, help="Increase verbosity") - options, args = parser.parse_args() + options = parser.parse_args() if not os.path.exists(options.config): - print "ERROR: config file %s does not exist. It is mandatory." % options.config - sys.exit(1) + print "ERROR: config file %s does not exist. It is mandatory." % options.config + sys.exit(1) - install(prefix=options.prefix,config_file=options.config,verbose=options.verbose) + install(prefix=options.prefix, config_file=options.config, verbose=options.verbose) pass # ----------------------------------------------------------------------------- diff --git a/bin/envSalome.py b/bin/envSalome.py index fb36c618d..3b7388f9f 100755 --- a/bin/envSalome.py +++ b/bin/envSalome.py @@ -36,7 +36,7 @@ import sys import setenv kernel_root=os.getenv("KERNEL_ROOT_DIR") -sys.path[:0]=[kernel_root+"/bin/salome"] +sys.path[:0]=[os.path.join(kernel_root,"bin","salome")] argv = sys.argv[1:] sys.argv = argv[1:] diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 385454a9a..0ffb397e3 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -32,8 +32,10 @@ # import os, sys, pickle, signal, commands,glob +import subprocess +import shlex from salome_utils import verbose -import salome_utils + def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None): """ @@ -195,7 +197,7 @@ def shutdownMyPort(port, cleanup=True): try: import time from omniORB import CORBA - + from LifeCycleCORBA import LifeCycleCORBA # shutdown all orb = CORBA.ORB_init([''], CORBA.ORB_ID) @@ -224,17 +226,19 @@ def __killMyPort(port, filedict): from salome_utils import generateFileName if sys.platform == "win32": username = os.getenv( "USERNAME" ) + tmpdir = 'c:\tmp' else: username = os.getenv('USER') - path = os.path.join('/tmp/logs', username) + tmpdir = '/tmp' + path = os.path.join(tmpdir, 'logs', username) fpidomniNames = generateFileName(path, prefix="", suffix="Pid_omniNames", extension="log", with_port=port) if not sys.platform == 'win32': - cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames ) - a = os.system(cmd) + cmd = 'pid=$(ps -eo pid,command | egrep "[0-9] omniNames -start {0}") ; echo $pid > {1}'.format(port, fpidomniNames ) + subprocess.call(cmd, shell=True) pass try: with open(fpidomniNames) as fpidomniNamesFile: @@ -245,7 +249,7 @@ def __killMyPort(port, filedict): try: pidfield = l.split()[0] # pid should be at the first position if sys.platform == "win32": - import win32pm + import win32pm #@UnresolvedImport if verbose(): print 'stop process '+pidfield+' : omniNames' win32pm.killpid(int(pidfield),0) else: @@ -267,12 +271,10 @@ def __killMyPort(port, filedict): if verbose(): print "stop process %s : %s"% (pid, cmd[0]) if cmd[0] == "omniNames": if not sys.platform == 'win32': - import subprocess - import shlex proc1 = subprocess.Popen(shlex.split('ps -eo pid,command'),stdout=subprocess.PIPE) proc2 = subprocess.Popen(shlex.split('egrep "[0-9] omniNames -start"'),stdin=proc1.stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE) proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits. - out,err=proc2.communicate() + out,_ = proc2.communicate() # out looks like: PID omniNames -start PORT # extract omninames pid and port number @@ -286,7 +288,7 @@ def __killMyPort(port, filedict): from PortManager import releasePort releasePort(omniNamesPort) os.kill(int(omniNamesPid),signal.SIGKILL) - except (ImportError, AttributeError, OSError) as e: + except (ImportError, AttributeError, OSError): pass except: import traceback @@ -294,7 +296,7 @@ def __killMyPort(port, filedict): try: if sys.platform == "win32": - import win32pm + import win32pm #@UnresolvedImport @Reimport win32pm.killpid(int(pid),0) else: os.kill(int(pid),signal.SIGKILL) @@ -312,6 +314,7 @@ def __killMyPort(port, filedict): # os.remove(filedict) cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"' +# pid = subprocess.check_output(shlex.split(cmd)) pid = commands.getoutput(cmd) a = "" while pid and len(a.split()) < 2: @@ -375,7 +378,6 @@ def killMyPort(port): time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up) try: - import PortManager filedict = getPiDict(port) #filedict = __guessPiDictFilename(port) import glob @@ -414,7 +416,7 @@ def killMyPortSpy(pid, port): dt = 1.0 while 1: if sys.platform == "win32": - from win32pm import killpid + from win32pm import killpid #@UnresolvedImport if killpid(int(pid), 0) != 0: return else: @@ -437,7 +439,7 @@ def killMyPortSpy(pid, port): orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID) import SALOME_NamingServicePy ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb) - import SALOME + import SALOME #@UnresolvedImport @UnusedImport session = ns.Resolve("/Kernel/Session") assert session except: @@ -472,7 +474,7 @@ if __name__ == "__main__": sys.exit(0) pass try: - from salomeContextUtils import setOmniOrbUserPath + from salomeContextUtils import setOmniOrbUserPath #@UnresolvedImport setOmniOrbUserPath() except Exception, e: print e diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py index 9c4c39e0a..4d003a386 100755 --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -26,7 +26,7 @@ import xml.sax import optparse import types -from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir +from salome_utils import verbose, getPortNumber, getHomeDir from salomeContextUtils import getScriptsAndArgs @@ -105,11 +105,13 @@ def version(): try: filename = None root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found - if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ): - filename = root_dir + "/bin/salome/VERSION" + version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION') + if root_dir and os.path.exists( version_file ): + filename = version_file root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found - if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ): - filename = root_dir + "/bin/salome/VERSION" + version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION') + if root_dir and os.path.exists( version_file ): + filename = version_file if filename: str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0" match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str ) @@ -127,7 +129,12 @@ def version_id(fname): major = minor = release = dev1 = dev2 = 0 vers = fname.split(".") if len(vers) > 0: major = int(vers[0]) - if len(vers) > 1: minor = int(vers[1]) + try: + if len(vers) > 1: minor = int(vers[1]) + except ValueError: + # If salome version given is 7.DEV, the call to int('DEV') will fail with + # a ValueError exception + pass if len(vers) > 2: mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I) if mr: @@ -160,15 +167,14 @@ def version_id(fname): ### def defaultUserFile(appname=salomeappname, cfgname=salomecfgname): v = version() - if v: v = ".%s" % v if sys.platform == "win32": - filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v)) + filename = os.path.join(getHomeDir(), "{0}.xml.{1}".format(appname, v)) else: if cfgname: - filename = os.path.join(getHomeDir(), ".config", cfgname, "%src%s" % (appname, v)) + filename = os.path.join(getHomeDir(), ".config", cfgname, "{0}rc.{1}".format(appname, v)) pass else: - filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v)) + filename = os.path.join(getHomeDir(), "{0}rc.{1}".format(appname, v)) pass pass return filename @@ -196,17 +202,17 @@ def userFile(appname, cfgname): # ... get all existing user preferences files if sys.platform == "win32": - files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname)) + files = glob.glob(os.path.join(getHomeDir(), "{0}.xml.*".format(appname))) else: files = [] if cfgname: # Since v6.6.0 - in ~/.config/salome directory, without dot prefix - files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "{0}rc.*".format(appname))) # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility) - files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".{0}rc.*".format(appname))) pass # old style (before v6.5.0) - in ~ directory, dot-prefixed - files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".{0}rc.*".format(appname))) pass # ... loop through all files and find most appopriate file (with closest id) @@ -215,9 +221,9 @@ def userFile(appname, cfgname): for f in files: ff = os.path.basename( f ) if sys.platform == "win32": - match = re.search( r'^%s\.xml\.([a-zA-Z0-9.]+)$'%appname, ff ) + match = re.search( r'^{0}\.xml\.([a-zA-Z0-9.]+)$'.format(appname), ff ) else: - match = re.search( r'^\.?%src\.([a-zA-Z0-9.]+)$'%appname, ff ) + match = re.search( r'^\.?{0}rc\.([a-zA-Z0-9.]+)$'.format(appname), ff ) if match: ver = version_id(match.group(1)) if not ver: continue # bad version id -> skip file @@ -352,7 +358,7 @@ class xml_parser: pass def endElement(self, name): - p = self.space.pop() + self.space.pop() self.current = None if self.section != section_to_skip and name == sec_tag: self.section = section_to_skip @@ -903,10 +909,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn global args config_var = appname+'Config' - separator = ":" - if os.sys.platform == 'win32': - separator = ";" - # check KERNEL_ROOT_DIR kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None) if kernel_root_dir is None: @@ -941,20 +943,22 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn dirs = [] if os.getenv(config_var): if sys.platform == 'win32': - dirs += re.split(';', os.getenv(config_var)) + dirs += re.split(os.pathsep, os.getenv(config_var)) else: dirs += re.split('[;|:]', os.getenv(config_var)) gui_available = True - if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ): - dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"] + gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui') + if os.getenv("GUI_ROOT_DIR") and os.path.isdir( gui_resources_dir ): + dirs.append(gui_resources_dir) pass else: gui_available = False - if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ): - dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"] + kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),'bin','salome','appliskel') + if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( kernel_resources_dir ): + dirs.append(kernel_resources_dir) pass - os.environ[config_var] = separator.join(dirs) + os.environ[config_var] = os.pathsep.join(dirs) dirs.reverse() # reverse order, like in "path" variable - FILO-style processing @@ -1176,7 +1180,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn #################################################### # Add values to args for add_opt in theAdditionalOptions: - cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest) + cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest) exec(cmd) #################################################### @@ -1191,15 +1195,15 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn dirs = re.split('[;]', os.environ[config_var] ) else: dirs = re.split('[;|:]', os.environ[config_var] ) - for m in args[modules_nam]: - if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m): - d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower() - d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources" + for module in args[modules_nam]: + if module not in ["KERNEL", "GUI", ""] and os.getenv("{0}_ROOT_DIR".format(module)): + d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources",module.lower()) + d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources") #if os.path.exists( "%s/%s.xml"%(d1, appname) ): - if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ): + if os.path.exists( os.path.join(d1,"{0}.xml".format(salomeappname)) ): dirs.append( d1 ) #elif os.path.exists( "%s/%s.xml"%(d2, appname) ): - elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ): + elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ): dirs.append( d2 ) else: #print "* '"+m+"' should be deleted from ",args[modules_nam] @@ -1231,6 +1235,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn args[useport_nam] = cmd_opts.use_port # return arguments - os.environ[config_var] = separator.join(dirs) + os.environ[config_var] = os.pathsep.join(dirs) #print "Args: ", args return args diff --git a/bin/nameserver.py b/bin/nameserver.py index ce1402ba7..56c100269 100755 --- a/bin/nameserver.py +++ b/bin/nameserver.py @@ -22,23 +22,23 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -import sys, os, re, socket +import os, sys, re, socket #import commands -from server import * +from server import Server from Utils_Identity import getShortHostName from launchConfigureParser import verbose # ----------------------------------------------------------------------------- class NamingServer(Server): - XTERM="" - USER=os.getenv('USER') - if USER is None: - USER='anonymous' - #os.system("mkdir -m 777 -p /tmp/logs") - LOGDIR="/tmp/logs/" + USER - - def initNSArgs(self): + XTERM = "" + USER = os.getenv('USER') + if USER is None: + USER = 'anonymous' + #os.system("mkdir -m 777 -p /tmp/logs") + LOGDIR = "/tmp/logs/" + USER + + def initNSArgs(self): if sys.platform == "win32": # temporarily using home directory for Namning Service logs # to be replaced with TEMP later... @@ -55,9 +55,9 @@ class NamingServer(Server): upath = os.environ["BaseDir"] + "/logs/"; if sys.platform == "win32": - upath += os.environ["Username"]; + upath += os.environ["Username"]; else: - upath += os.environ["USER"]; + upath += os.environ["USER"]; try: os.mkdir(upath) @@ -68,16 +68,15 @@ class NamingServer(Server): if verbose(): print "Name Service... ", #hname=os.environ["HOST"] #commands.getoutput("hostname") if sys.platform == "win32": - hname=getShortHostName(); + hname = getShortHostName(); else: hname = socket.gethostname(); #print "hname=",hname - f=open(os.environ["OMNIORB_CONFIG"]) - ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read()) - if verbose(): print "ss = ", ss, - f.close() - sl=ss[0] + with open(os.environ["OMNIORB_CONFIG"]) as f: + ss = re.findall("NameService=corbaname::" + hname + ":\d+", f.read()) + if verbose(): print "ss = ", ss, + sl = ss[0] ll = sl.split(':') aPort = ll[-1] #aPort=(ss.join().split(':'))[2]; @@ -91,15 +90,15 @@ class NamingServer(Server): upath += "/omniNames_%s"%(aPort) try: - os.mkdir(upath) + os.mkdir(upath) except: - #print "Can't create " + upath - pass + #print "Can't create " + upath + pass #os.system("touch " + upath + "/dummy") for fname in os.listdir(upath): try: - os.remove(upath + "/" + fname) + os.remove(upath + "/" + fname) except: pass #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log") @@ -110,24 +109,24 @@ class NamingServer(Server): #print "port=", aPort if sys.platform == "win32": #print "start omniNames -start " + aPort + " -logdir " + upath - self.CMD=['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))] + self.CMD = ['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))] #os.system("start omniNames -start " + aPort + " -logdir " + upath) else: #self.CMD=['omniNames -start ' , aPort , ' -logdir ' , upath , ' &'] - self.CMD=['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log'] + self.CMD = ['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log'] #os.system("omniNames -start " + aPort + " -logdir " + upath + " &") if verbose(): print "... ok" if verbose(): print "to list contexts and objects bound into the context with the specified name : showNS " - def initArgs(self): + def initArgs(self): Server.initArgs(self) if sys.platform == "win32": - env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("PATH")] + env_ld_library_path = ['env', 'LD_LIBRARY_PATH=' + os.getenv("PATH")] else: - env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")] - self.CMD=['xterm', '-e']+ env_ld_library_path + ['python'] + env_ld_library_path = ['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")] + self.CMD = ['xterm', '-e']+ env_ld_library_path + ['python'] self.initNSArgs() # In LifeCycleCORBA, FactoryServer is started with rsh on the requested diff --git a/bin/orbmodule.py b/bin/orbmodule.py index dc280ce81..97ef010bb 100755 --- a/bin/orbmodule.py +++ b/bin/orbmodule.py @@ -27,7 +27,7 @@ import sys,os,time import string -from nameserver import * +from nameserver import NamingServer from omniORB import CORBA from launchConfigureParser import verbose @@ -37,18 +37,18 @@ import CosNaming # ----------------------------------------------------------------------------- class client: - """Client for SALOME""" + """Client for SALOME""" - def __init__(self,args=None): + def __init__(self,args=None): # Initialise the ORB self.orb=CORBA.ORB_init(sys.argv, CORBA.ORB_ID) # Initialise the Naming Service self.initNS(args or {}) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def initNS(self,args): + def initNS(self,args): # Obtain a reference to the root naming context obj = self.orb.resolve_initial_references("NameService") try: @@ -61,11 +61,11 @@ class client: # On lance le Naming Server (doit etre dans le PATH) test = True if args['wake_up_session']: - test = False - pass + test = False + pass if test: - NamingServer(args).run() - pass + NamingServer(args).run() + pass print "Searching Naming Service ", ncount=0 delta=0.1 @@ -86,42 +86,42 @@ class client: sys.exit(1) print " found in %s seconds " % ((ncount-1)*delta) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def showNScontext(self,context,dec=''): + def showNScontext(self,context,dec=''): if not context: - print "[NS] No context" - return + print "[NS] No context" + return else: - print context + print context - bl,bi=context.list(0) + _,bi = context.list(0) if bi is not None: - ok,b=bi.next_one() - while(ok): + ok,b = bi.next_one() + while(ok): for s in b.binding_name : - print "%s%s.%s" %(dec,s.id,s.kind) - if s.kind == "dir": - obj=context.resolve([s]) + print "%s%s.%s" %(dec,s.id,s.kind) + if s.kind == "dir": + obj = context.resolve([s]) scontext = obj._narrow(CosNaming.NamingContext) self.showNScontext(scontext,dec=dec+' ') - ok,b=bi.next_one() + ok,b = bi.next_one() - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def showNS(self): + def showNS(self): """ Show the content of SALOME naming service """ self.showNScontext(self.rootContext) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def Resolve(self, Path): - resolve_path=string.split(Path,'/') + def Resolve(self, Path): + resolve_path = string.split(Path,'/') if resolve_path[0] == '': del resolve_path[0] - dir_path=resolve_path[:-1] - context_name=[] + dir_path = resolve_path[:-1] + context_name = [] for e in dir_path: - context_name.append(CosNaming.NameComponent(e,"dir")) + context_name.append(CosNaming.NameComponent(e,"dir")) context_name.append(CosNaming.NameComponent(resolve_path[-1],"object")) try: @@ -136,16 +136,16 @@ class client: obj = None return obj - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def waitNS(self,name,typobj=None,maxcount=240): - count=0 - delta=0.5 + def waitNS(self,name,typobj=None,maxcount=240): + count = 0 + delta = 0.5 print "Searching %s in Naming Service " % name, while(1): count += 1 if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name - obj=self.Resolve(name) + obj = self.Resolve(name) if obj : print " found in %s seconds " % ((count-1)*delta) break @@ -161,42 +161,42 @@ class client: print "%s exists but is not a %s" % (name,typobj) return nobj - if sys.platform != "win32": - def waitNSPID(self, theName, thePID, theTypObj = None): - aCount = 0 - aDelta = 0.5 - anObj = None - print "Searching %s in Naming Service " % theName, - while(1): - try: - os.kill(thePID,0) - except: - raise RuntimeError, "Process %d for %s not found" % (thePID,theName) - aCount += 1 - anObj = self.Resolve(theName) - if anObj: + if sys.platform != "win32": + def waitNSPID(self, theName, thePID, theTypObj = None): + aCount = 0 + aDelta = 0.5 + anObj = None + print "Searching %s in Naming Service " % theName, + while(1): + try: + os.kill(thePID,0) + except: + raise RuntimeError, "Process %d for %s not found" % (thePID,theName) + aCount += 1 + anObj = self.Resolve(theName) + if anObj: print " found in %s seconds " % ((aCount-1)*aDelta) break - else: + else: sys.stdout.write('+') sys.stdout.flush() time.sleep(aDelta) pass - pass - - if theTypObj is None: - return anObj - - anObject = anObj._narrow(theTypObj) - if anObject is None: - print "%s exists but is not a %s" % (theName,theTypObj) - return anObject + pass + + if theTypObj is None: + return anObj + + anObject = anObj._narrow(theTypObj) + if anObject is None: + print "%s exists but is not a %s" % (theName,theTypObj) + return anObject - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def ResolveLogger(self, name): - context_name=[] + def ResolveLogger(self, name): + context_name = [] context_name.append(CosNaming.NameComponent(name,"")) try: @@ -211,16 +211,16 @@ class client: obj = None return obj - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def waitLogger(self,name,typobj=None,maxcount=40): - count=0 - delta=0.5 + def waitLogger(self,name,typobj=None,maxcount=40): + count = 0 + delta = 0.5 print "Searching %s in Naming Service " % name, while(1): count += 1 if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name - obj=self.ResolveLogger(name) + obj = self.ResolveLogger(name) if obj : print " found in %s seconds " % ((count-1)*delta) break diff --git a/bin/parseConfigFile.py b/bin/parseConfigFile.py index 2f2bbb2ea..212b646a4 100644 --- a/bin/parseConfigFile.py +++ b/bin/parseConfigFile.py @@ -23,7 +23,7 @@ import logging import re from io import StringIO import subprocess -from salomeContextUtils import SalomeContextException +from salomeContextUtils import SalomeContextException #@UnresolvedImport logging.basicConfig() logConfigParser = logging.getLogger(__name__) @@ -133,7 +133,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser): cursect[optname][0] += ','+optval else: cursect[optname] = [optval] - # END OF SUBSITUTION + # END OF SUBSTITUTION else: # valueless option handling cursect[optname] = optval diff --git a/bin/runConsole.py b/bin/runConsole.py index 57c54d0ed..28c3df185 100644 --- a/bin/runConsole.py +++ b/bin/runConsole.py @@ -29,7 +29,7 @@ def __prompt(environment = None, commands=None, message = "Connecting to SALOME" commands = [] import code - import rlcompleter + import rlcompleter #@UnusedImport import readline readline.parse_and_bind("tab: complete") # calling this with globals ensures we can see the environment diff --git a/bin/salome_utils.py b/bin/salome_utils.py index a27009a45..f20f67276 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -208,24 +208,8 @@ def getHomeDir(): """ Get home directory. """ - import os, sys - if sys.platform == "win32": - # for Windows the home directory is detected in the following way: - # 1. try USERPROFILE env variable - # 2. try combination of HOMEDRIVE and HOMEPATH env variables - # 3. try HOME env variable - # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used - dir = os.getenv("USERPROFILE") - if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"): - dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH")) - if not dir: - dir = os.getenv("HOME") - pass - else: - # for Linux: use HOME variable - dir = os.getenv("HOME") - pass - return dir + import os + return os.path.realpath(os.path.expanduser('~')) # --- def getTmpDir(): -- 2.39.2