X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=bin%2FlaunchConfigureParser.py;h=c7eb5157c304bbb69e3f986180d6a6944ae64efb;hb=a4874256219c549a9b1ff740d549391c4bf2f25f;hp=647e992308819e44d3e0560e8a01ad3cb7f5e055;hpb=755e4a1a2d81db80a3a46d3c2d55d74e1853d5bf;p=modules%2Fkernel.git diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py old mode 100755 new mode 100644 index 647e99230..c7eb5157c --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -1,5 +1,5 @@ # -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE +# Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE # # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS @@ -21,14 +21,15 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -import os, glob, string, sys, re +import argparse +import glob +import os +import re +import sys import xml.sax -import optparse -import types from salome_utils import verbose, getPortNumber, getHomeDir -from salomeContextUtils import getScriptsAndArgs # names of tags in XML configuration file doc_tag = "document" @@ -62,16 +63,15 @@ pinter_nam = "pinter" batch_nam = "batch" test_nam = "test" play_nam = "play" +lang_nam = "language" gdb_session_nam = "gdb_session" ddd_session_nam = "ddd_session" valgrind_session_nam = "valgrind_session" shutdown_servers_nam = "shutdown_servers" foreground_nam = "foreground" wake_up_session_nam = "wake_up_session" -siman_nam = "siman" -siman_study_nam = "siman_study" -siman_scenario_nam = "siman_scenario" -siman_user_nam = "siman_user" +launcher_only_nam = "launcher_only" +launcher_nam = "launcher" # values in XML configuration file giving specific module parameters ( section) # which are stored in opts with key _ (eg SMESH_plugins) @@ -91,8 +91,9 @@ standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"] # values of boolean type (must be '0' or '1'). # xml_parser.boolValue() is used for correct setting -boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam ) +boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam, launcher_only_nam ) intKeys = ( interp_nam, ) +strKeys = ( launcher_nam ) # values of list type listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam ) @@ -113,11 +114,12 @@ def 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 ) + with open(filename, "r") as f: + v = f.readline() # v = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0" + match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', v ) if match : return match.group( 1 ) - except: + except Exception: pass return '' @@ -128,7 +130,13 @@ def version(): def version_id(fname): major = minor = release = dev1 = dev2 = 0 vers = fname.split(".") - if len(vers) > 0: major = int(vers[0]) + if len(vers) > 0: + try: + major = int(vers[0]) + except ValueError: + # If salome version given is DEV, the call to int('DEV') will fail with + # a ValueError exception + pass try: if len(vers) > 1: minor = int(vers[1]) except ValueError: @@ -212,7 +220,7 @@ def userFile(appname, cfgname): files += glob.glob(os.path.join(getHomeDir(), filetmpl2.format(appname))) pass - # ... loop through all files and find most appopriate file (with closest id) + # ... loop through all files and find most appropriate file (with closest id) appr_id = -1 appr_file = "" for f in files: @@ -240,14 +248,14 @@ def userFile(appname, cfgname): def process_containers_params( standalone, embedded ): # 1. filter inappropriate containers names if standalone is not None: - standalone = filter( lambda x: x in standalone_choices, standalone ) + standalone = [x for x in standalone if x in standalone_choices] if embedded is not None: - embedded = filter( lambda x: x in embedded_choices, embedded ) + embedded = [x for x in embedded if x in embedded_choices] # 2. remove containers appearing in 'standalone' parameter from the 'embedded' # parameter --> i.e. 'standalone' parameter has higher priority if standalone is not None and embedded is not None: - embedded = filter( lambda x: x not in standalone, embedded ) + embedded = [x for x in embedded if x not in standalone] # 3. return corrected parameters values return standalone, embedded @@ -263,7 +271,7 @@ section_to_skip = "" class xml_parser: def __init__(self, fileName, _opts, _importHistory): #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call - if verbose(): print "Configure parser: processing %s ..." % fileName + if verbose(): print("Configure parser: processing %s ..." % fileName) self.fileName = os.path.abspath(fileName) self.importHistory = _importHistory self.importHistory.append(self.fileName) @@ -281,34 +289,46 @@ class xml_parser: self.opts[ embedded_nam ] = embedded pass - def boolValue( self, str ): - strloc = str - if isinstance(strloc, types.UnicodeType): + def boolValue( self, item): + strloc = item + if isinstance(strloc, str): strloc = strloc.encode().strip() - if isinstance(strloc, types.StringType): - strlow = strloc.lower() - if strlow in ("1", "yes", "y", "on", "true", "ok"): + if isinstance(strloc, bytes): + strlow = strloc.decode().lower() + if strlow in ("1", "yes", "y", "on", "true", "ok"): return True elif strlow in ("0", "no", "n", "off", "false", "cancel"): return False return strloc pass - def intValue( self, str ): - strloc = str - if isinstance(strloc, types.UnicodeType): + def intValue( self, item): + strloc = item + if isinstance(strloc, str): strloc = strloc.encode().strip() - if isinstance(strloc, types.StringType): - strlow = strloc.lower() - if strlow in ("1", "yes", "y", "on", "true", "ok"): + if isinstance(strloc, bytes): + strlow = strloc.decode().lower() + if strlow in ("1", "yes", "y", "on", "true", "ok"): return 1 elif strlow in ("0", "no", "n", "off", "false", "cancel"): return 0 else: - return string.atoi(strloc) + return int(strloc.decode()) return strloc pass + def strValue( self, item): + strloc = item + try: + if isinstance( strloc, str): + strloc = strloc.strip() + else: + if isinstance( strloc, bytes): + strloc = strloc.decode().strip() + except Exception: + pass + return strloc + def startElement(self, name, attrs): self.space.append(name) self.current = None @@ -321,9 +341,9 @@ class xml_parser: # either "launch" or module name -- set section_name if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames(): section_name = attrs.getValue( nam_att ) - if section_name == lanch_nam: + if section_name in [lanch_nam, lang_nam]: self.section = section_name # launch section - elif self.opts.has_key( modules_nam ) and \ + elif modules_nam in self.opts and \ section_name in self.opts[ modules_nam ]: self.section = section_name # section else: @@ -343,14 +363,17 @@ class xml_parser: key = nam else: # key for section key = self.section + "_" + nam + key = self.strValue( key ) if nam in boolKeys: self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1 elif nam in intKeys: self.opts[key] = self.intValue( val ) # assign integer value + elif nam in strKeys: + self.opts[key] = val # assign value elif nam in listKeys: - self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: [] + self.opts[key] = [ self.strValue( a ) for a in re.split( "[:;,]", val ) ] # assign list value: [] else: - self.opts[key] = val + self.opts[key] = self.strValue( val ) # string value pass pass @@ -390,12 +413,12 @@ class xml_parser: if os.path.exists(absfname + ext) : absfname += ext if absfname in self.importHistory : - if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname + if verbose(): print("Configure parser: Warning : file %s is already imported" % absfname) return # already imported break pass else: - if verbose(): print "Configure parser: Error : file %s does not exist" % absfname + if verbose(): print("Configure parser: Error : file %s does not exist" % absfname) return # importing file @@ -406,464 +429,396 @@ class xml_parser: # import file imp = xml_parser(absfname, opts, self.importHistory) # merge results - for key in imp.opts.keys(): - if not self.opts.has_key(key): + for key in imp.opts: + if key not in self.opts: self.opts[key] = imp.opts[key] pass pass pass - except: - if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname + except Exception: + if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname) pass # ----------------------------------------------------------------------------- -booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True, - '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False } +booleans = {'1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True, + '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False} -boolean_choices = booleans.keys() +boolean_choices = list(booleans.keys()) -def check_embedded(option, opt, value, parser): - from optparse import OptionValueError - assert value is not None - if parser.values.embedded: - embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) ) - else: - embedded = [] - if parser.values.standalone: - standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) ) - else: - standalone = [] - vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) ) - for v in vals: - if v not in embedded_choices: - raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) ) - if v not in embedded: - embedded.append( v ) - if v in standalone: - del standalone[ standalone.index( v ) ] - pass - parser.values.embedded = ",".join( embedded ) - parser.values.standalone = ",".join( standalone ) - pass -def check_standalone(option, opt, value, parser): - from optparse import OptionValueError - assert value is not None - if parser.values.embedded: - embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) ) - else: - embedded = [] - if parser.values.standalone: - standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) ) - else: - standalone = [] - vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) ) - for v in vals: - if v not in standalone_choices: - raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) ) - if v not in standalone: - standalone.append( v ) - if v in embedded: - del embedded[ embedded.index( v ) ] - pass - parser.values.embedded = ",".join( embedded ) - parser.values.standalone = ",".join( standalone ) - pass +class CheckEmbeddedAction(argparse.Action): + def __call__(self, parser, namespace, value, option_string=None): + assert value is not None + if namespace.embedded: + embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()] + else: + embedded = [] + if namespace.standalone: + standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()] + else: + standalone = [] + vals = [a for a in re.split("[:;,]", value) if a.strip()] + for v in vals: + if v not in embedded_choices: + raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)" + % (self.dest, v, ", ".join(map(repr, embedded_choices)))) + if v not in embedded: + embedded.append(v) + if v in standalone: + del standalone[standalone.index(v)] + pass + namespace.embedded = ",".join(embedded) + namespace.standalone = ",".join(standalone) + pass -def store_boolean (option, opt, value, parser, *args): - if isinstance(value, types.StringType): - try: - value_conv = booleans[value.strip().lower()] - for attribute in args: - setattr(parser.values, attribute, value_conv) - except KeyError: - raise optparse.OptionValueError( - "option %s: invalid boolean value: %s (choose from %s)" - % (opt, value, boolean_choices)) - else: - for attribute in args: - setattr(parser.values, attribute, value) -def CreateOptionParser (theAdditionalOptions=None): - if theAdditionalOptions is None: - theAdditionalOptions = [] +class CheckStandaloneAction(argparse.Action): + def __call__(self, parser, namespace, value, option_string=None): + assert value is not None + if namespace.embedded: + embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()] + else: + embedded = [] + if namespace.standalone: + standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()] + else: + standalone = [] + vals = [a for a in re.split("[:;,]", value) if a.strip()] + for v in vals: + if v not in standalone_choices: + raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)" + % (self.dest, v, ", ".join(map(repr, standalone_choices)))) + if v not in standalone: + standalone.append(v) + if v in embedded: + del embedded[embedded.index(v)] + pass + namespace.embedded = ",".join(embedded) + namespace.standalone = ",".join(standalone) + + +class StoreBooleanAction(argparse.Action): + def __call__(self, parser, namespace, value, option_string=None): + if isinstance(value, bytes): + value = value.decode() + if isinstance(value, str): + try: + value_conv = booleans[value.strip().lower()] + setattr(namespace, self.dest, value_conv) + except KeyError: + raise argparse.ArgumentError( + "option %s: invalid boolean value: %s (choose from %s)" + % (self.dest, value, boolean_choices)) + else: + setattr(namespace, self.dest, value) + + +def CreateOptionParser(exeName=None): + + if not exeName: + exeName = "%(prog)s" + + a_usage = """%s [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]] +Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,... +""" % exeName + version_str = "Salome %s" % version() + pars = argparse.ArgumentParser(usage=a_usage) + + # Version + pars.add_argument('-v', '--version', action='version', version=version_str) + # GUI/Terminal. Default: GUI help_str = "Launch without GUI (in the terminal mode)." - o_t = optparse.Option("-t", - "--terminal", - action="store_false", - dest="gui", - help=help_str) + pars.add_argument("-t", + "--terminal", + action="store_false", + dest="gui", + help=help_str) help_str = "Launch in Batch Mode. (Without GUI on batch machine)" - o_b = optparse.Option("-b", - "--batch", - action="store_true", - dest="batch", - help=help_str) + pars.add_argument("-b", + "--batch", + action="store_true", + dest="batch", + help=help_str) help_str = "Launch in GUI mode [default]." - o_g = optparse.Option("-g", - "--gui", - action="store_true", - dest="gui", - help=help_str) + pars.add_argument("-g", + "--gui", + action="store_true", + dest="gui", + help=help_str) - # Show Desktop (inly in GUI mode). Default: True + # Show Desktop (only in GUI mode). Default: True help_str = "1 to activate GUI desktop [default], " help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). " help_str += "Ignored in the terminal mode." - o_d = optparse.Option("-d", - "--show-desktop", - metavar="<1/0>", - #type="choice", choices=boolean_choices, - type="string", - action="callback", callback=store_boolean, callback_args=('desktop',), - dest="desktop", - help=help_str) + pars.add_argument("-d", + "--show-desktop", + metavar="<1/0>", + action=StoreBooleanAction, + dest="desktop", + help=help_str) help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). " help_str += "The same as --show-desktop=0." - o_o = optparse.Option("-o", - "--hide-desktop", - action="store_false", - dest="desktop", - help=help_str) + pars.add_argument("-o", + "--hide-desktop", + action="store_false", + dest="desktop", + help=help_str) # Use logger or log-file. Default: nothing. help_str = "Redirect messages to the CORBA collector." - #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str) - o_l = optparse.Option("-l", - "--logger", - action="store_const", const="CORBA", - dest="log_file", - help=help_str) + pars.add_argument("-l", + "--logger", + action="store_const", const="CORBA", + dest="log_file", + help=help_str) help_str = "Redirect messages to the " - o_f = optparse.Option("-f", - "--log-file", - metavar="", - type="string", - action="store", - dest="log_file", - help=help_str) + pars.add_argument("-f", + "--log-file", + metavar="", + dest="log_file", + help=help_str) # Configuration XML file. Default: see defaultUserFile() function - help_str = "Parse application settings from the " + help_str = "Parse application settings from the " help_str += "instead of default %s" % defaultUserFile() - o_r = optparse.Option("-r", - "--resources", - metavar="", - type="string", - action="store", - dest="resources", - help=help_str) + pars.add_argument("-r", + "--resources", + metavar="", + dest="resources", + help=help_str) # Use own xterm for each server. Default: False. help_str = "Launch each SALOME server in own xterm console" - o_x = optparse.Option("-x", - "--xterm", - action="store_true", - dest="xterm", - help=help_str) + pars.add_argument("-x", + "--xterm", + action="store_true", + dest="xterm", + help=help_str) # Modules. Default: Like in configuration files. help_str = "SALOME modules list (where , are the names " help_str += "of SALOME modules which should be available in the SALOME session)" - o_m = optparse.Option("-m", - "--modules", - metavar="", - type="string", - action="append", - dest="modules", - help=help_str) + pars.add_argument("-m", + "--modules", + metavar="", + action="append", + dest="modules", + help=help_str) # Embedded servers. Default: Like in configuration files. help_str = "CORBA servers to be launched in the Session embedded mode. " help_str += "Valid values for : %s " % ", ".join( embedded_choices ) help_str += "[by default the value from the configuration files is used]" - o_e = optparse.Option("-e", - "--embedded", - metavar="", - type="string", - action="callback", - dest="embedded", - callback=check_embedded, - help=help_str) + pars.add_argument("-e", + "--embedded", + metavar="", + action=CheckEmbeddedAction, + dest="embedded", + help=help_str) # Standalone servers. Default: Like in configuration files. help_str = "CORBA servers to be launched in the standalone mode (as separate processes). " help_str += "Valid values for : %s " % ", ".join( standalone_choices ) help_str += "[by default the value from the configuration files is used]" - o_s = optparse.Option("-s", - "--standalone", - metavar="", - type="string", - action="callback", - dest="standalone", - callback=check_standalone, - help=help_str) + pars.add_argument("-s", + "--standalone", + metavar="", + action=CheckStandaloneAction, + dest="standalone", + help=help_str) # Kill with port. Default: False. help_str = "Kill SALOME with the current port" - o_p = optparse.Option("-p", - "--portkill", - action="store_true", - dest="portkill", - help=help_str) + pars.add_argument("-p", + "--portkill", + action="store_true", + dest="portkill", + help=help_str) # Kill all. Default: False. help_str = "Kill all running SALOME sessions" - o_k = optparse.Option("-k", - "--killall", - action="store_true", - dest="killall", - help=help_str) + pars.add_argument("-k", + "--killall", + action="store_true", + dest="killall", + help=help_str) # Additional python interpreters. Default: 0. help_str = "The number of additional external python interpreters to run. " help_str += "Each additional python interpreter is run in separate " help_str += "xterm session with properly set SALOME environment" - o_i = optparse.Option("-i", - "--interp", - metavar="", - type="int", - action="store", - dest="interp", - help=help_str) + pars.add_argument("-i", + "--interp", + metavar="", + type=int, + dest="interp", + help=help_str) # Splash. Default: True. help_str = "1 to display splash screen [default], " help_str += "0 to disable splash screen. " help_str += "This option is ignored in the terminal mode. " help_str += "It is also ignored if --show-desktop=0 option is used." - o_z = optparse.Option("-z", - "--splash", - metavar="<1/0>", - #type="choice", choices=boolean_choices, - type="string", - action="callback", callback=store_boolean, callback_args=('splash',), - dest="splash", - help=help_str) + pars.add_argument("-z", + "--splash", + metavar="<1/0>", + action=StoreBooleanAction, + dest="splash", + help=help_str) # Catch exceptions. Default: True. help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], " help_str += "0 (no,false,off,cancel) to disable centralized exception handling." - o_c = optparse.Option("-c", - "--catch-exceptions", - metavar="<1/0>", - #type="choice", choices=boolean_choices, - type="string", - action="callback", callback=store_boolean, callback_args=('catch_exceptions',), - dest="catch_exceptions", - help=help_str) + pars.add_argument("-c", + "--catch-exceptions", + metavar="<1/0>", + action=StoreBooleanAction, + dest="catch_exceptions", + help=help_str) # Print free port and exit help_str = "Print free port and exit" - o_a = optparse.Option("--print-port", - action="store_true", - dest="print_port", default=False, - help=help_str) + pars.add_argument("--print-port", + action="store_true", + dest="print_port", + help=help_str) + + # launch only omniNames and Launcher server + help_str = "launch only omniNames and Launcher server" + pars.add_argument("--launcher_only", + action="store_true", + dest="launcher_only", + help=help_str) + + # machine and port where is the Launcher + help_str = "machine and port where is the Launcher. Usage: " + help_str += "--launcher=machine:port" + pars.add_argument("--launcher", + metavar="<=machine:port>", + type=str, + dest="launcher", + help=help_str) # Do not relink ${HOME}/.omniORB_last.cfg help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg" - o_n = optparse.Option("--nosave-config", - action="store_false", - dest="save_config", default=True, - help=help_str) + pars.add_argument("--nosave-config", + action="store_false", + dest="save_config", + help=help_str) # Launch with interactive python console. Default: False. help_str = "Launch with interactive python console." - o_pi = optparse.Option("--pinter", - action="store_true", - dest="pinter", - help=help_str) + pars.add_argument("--pinter", + action="store_true", + dest="pinter", + help=help_str) # Print Naming service port into a user file. Default: False. help_str = "Print Naming Service Port into a user file." - o_nspl = optparse.Option("--ns-port-log", - metavar="", - type="string", - action="store", - dest="ns_port_log_file", - help=help_str) + pars.add_argument("--ns-port-log", + metavar="", + dest="ns_port_log_file", + help=help_str) # Write/read test script file with help of TestRecorder. Default: False. help_str = "Write/read test script file with help of TestRecorder." - o_test = optparse.Option("--test", - metavar="", - type="string", - action="store", - dest="test_script_file", - help=help_str) + pars.add_argument("--test", + metavar="", + dest="test_script_file", + help=help_str) # Reproducing test script with help of TestRecorder. Default: False. help_str = "Reproducing test script with help of TestRecorder." - o_play = optparse.Option("--play", - metavar="", - type="string", - action="store", - dest="play_script_file", - help=help_str) + pars.add_argument("--play", + metavar="", + dest="play_script_file", + help=help_str) # gdb session help_str = "Launch session with gdb" - o_gdb = optparse.Option("--gdb-session", - action="store_true", - dest="gdb_session", default=False, - help=help_str) + pars.add_argument("--gdb-session", + action="store_true", + dest="gdb_session", + help=help_str) # ddd session help_str = "Launch session with ddd" - o_ddd = optparse.Option("--ddd-session", - action="store_true", - dest="ddd_session", default=False, - help=help_str) + pars.add_argument("--ddd-session", + action="store_true", + dest="ddd_session", + help=help_str) # valgrind session help_str = "Launch session with valgrind $VALGRIND_OPTIONS" - o_valgrind = optparse.Option("--valgrind-session", - action="store_true", - dest="valgrind_session", default=False, - help=help_str) + pars.add_argument("--valgrind-session", + action="store_true", + dest="valgrind_session", + help=help_str) # shutdown-servers. Default: False. help_str = "1 to shutdown standalone servers when leaving python interpreter, " help_str += "0 to keep the standalone servers as daemon [default]. " help_str += "This option is only useful in batchmode " help_str += "(terminal mode or without showing desktop)." - o_shutdown = optparse.Option("-w", - "--shutdown-servers", - metavar="<1/0>", - #type="choice", choices=boolean_choices, - type="string", - action="callback", callback=store_boolean, callback_args=('shutdown_servers',), - dest="shutdown_servers", - help=help_str) + pars.add_argument("-w", + "--shutdown-servers", + metavar="<1/0>", + action=StoreBooleanAction, + dest="shutdown_servers", + help=help_str) # foreground. Default: True. help_str = "0 and runSalome exits after have launched the gui, " help_str += "1 to launch runSalome in foreground mode [default]." - o_foreground = optparse.Option("--foreground", - metavar="<1/0>", - #type="choice", choices=boolean_choices, - type="string", - action="callback", callback=store_boolean, callback_args=('foreground',), - dest="foreground", - help=help_str) + pars.add_argument("--foreground", + metavar="<1/0>", + action=StoreBooleanAction, + dest="foreground", + help=help_str) # wake up session help_str = "Wake up a previously closed session. " help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. " - help_str += "If this variable is not setted, the last configuration is taken. " - o_wake_up = optparse.Option("--wake-up-session", - action="store_true", - dest="wake_up_session", default=False, - help=help_str) + help_str += "If this variable is not set, the last configuration is taken. " + pars.add_argument("--wake-up-session", + action="store_true", + dest="wake_up_session", default=False, + help=help_str) # server launch mode help_str = "Mode used to launch server processes (daemon or fork)." - o_slm = optparse.Option("--server-launch-mode", - metavar="", - type="choice", - choices=["daemon","fork"], - action="store", - dest="server_launch_mode", - help=help_str) + pars.add_argument("--server-launch-mode", + metavar="", + choices=["daemon", "fork"], + dest="server_launch_mode", + help=help_str) # use port help_str = "Preferable port SALOME to be started on. " help_str += "If specified port is not busy, SALOME session will start on it; " help_str += "otherwise, any available port will be searched and used." - o_port = optparse.Option("--port", - metavar="", - type="int", - action="store", - dest="use_port", - help=help_str) - - # SIMAN launch mode - help_str = "Special mode for interacting with SIMAN." - o_siman = optparse.Option("--siman", - action="store_true", - dest="siman", - help=help_str) - - # SIMAN study - help_str = "SIMAN study identifier." - o_siman_study = optparse.Option("--siman-study", - metavar="", - type="string", - action="store", - dest="siman_study", - help=help_str) - - # SIMAN scenario - help_str = "SIMAN scenario identifier." - o_siman_scenario = optparse.Option("--siman-scenario", - metavar="", - type="string", - action="store", - dest="siman_scenario", - help=help_str) - - # SIMAN user - help_str = "SIMAN user identifier." - o_siman_user = optparse.Option("--siman-user", - metavar="", - type="string", - action="store", - dest="siman_user", - help=help_str) - - # All options - opt_list = [o_t,o_g, # GUI/Terminal - o_d,o_o, # Desktop - o_b, # Batch - o_l,o_f, # Use logger or log-file - o_r, # Configuration XML file - o_x, # xterm - o_m, # Modules - o_e, # Embedded servers - o_s, # Standalone servers - o_p, # Kill with port - o_k, # Kill all - o_i, # Additional python interpreters - o_z, # Splash - o_c, # Catch exceptions - o_a, # Print free port and exit - o_n, # --nosave-config - o_pi, # Interactive python console - o_nspl, - o_test, # Write/read test script file with help of TestRecorder - o_play, # Reproducing test script with help of TestRecorder - o_gdb, - o_ddd, - o_valgrind, - o_shutdown, - o_foreground, - o_wake_up, - o_slm, # Server launch mode - o_port, # Use port - o_siman, # Siman launch mode - o_siman_study, # Siman study - o_siman_scenario,# Siman scenario - o_siman_user, # Siman user - ] - - #std_options = ["gui", "desktop", "log_file", "resources", - # "xterm", "modules", "embedded", "standalone", - # "portkill", "killall", "interp", "splash", - # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"] - - opt_list += theAdditionalOptions - - a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]] -Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,... -""" - version_str = "Salome %s" % version() - pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list) + pars.add_argument("--port", + metavar="", + type=int, + dest="use_port", + help=help_str) + + # Language + help_str = "Force application language. By default, a language specified in " + help_str += "the user's preferences is used." + pars.add_argument("-a", + "--language", + dest="language", + help=help_str) + + # Positional arguments (hdf file, python file) + pars.add_argument("arguments", nargs=argparse.REMAINDER) return pars @@ -877,7 +832,7 @@ Python file arguments, if any, must be comma-separated (without blank characters args = {} #def get_env(): #args = [] -def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname): +def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None, keepEnvironment=True): ### # Collect launch configuration files: # - The environment variable "Config" (SalomeAppConfig) which can @@ -891,7 +846,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn # - These directories are analyzed beginning from the last one in the list, # so the first directory listed in "Config" environment variable # has higher priority: it means that if some configuration options - # is found in the next analyzed cofiguration file - it will be replaced + # is found in the next analyzed configuration file - it will be replaced # - The last configuration file which is parsed is user configuration file # situated in the home directory (if it exists): # * ~/.config/salome/.rc[.]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0) @@ -899,33 +854,29 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn # - Command line options have the highest priority and replace options # specified in configuration file(s) ### - - if theAdditionalOptions is None: - theAdditionalOptions = [] - global args config_var = appname+'Config' # check KERNEL_ROOT_DIR kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None) if kernel_root_dir is None: - print """ + print(""" For each SALOME module, the environment variable _ROOT_DIR must be set. KERNEL_ROOT_DIR is mandatory. - """ + """) sys.exit(1) ############################ # parse command line options - pars = CreateOptionParser(theAdditionalOptions) - (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:]) + pars = CreateOptionParser(exeName=exeName) + cmd_opts = pars.parse_args(sys.argv[1:]) ############################ # Process --print-port option if cmd_opts.print_port: from searchFreePort import searchFreePort searchFreePort({}) - print "port:%s"%(os.environ['NSPORT']) + print("port:%s"%(os.environ['NSPORT'])) try: import PortManager @@ -944,40 +895,39 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn else: dirs += re.split('[;|:]', os.getenv(config_var)) - gui_available = False - if os.getenv("GUI_ROOT_DIR"): - gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui') - if os.path.isdir( gui_resources_dir ): - gui_available = True - dirs.append(gui_resources_dir) - pass - if not gui_available: - 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] = os.pathsep.join(dirs) + if not keepEnvironment: + if os.getenv("GUI_ROOT_DIR") and os.path.isdir(os.getenv("GUI_ROOT_DIR")): + gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui') + if os.path.isdir(gui_resources_dir): + dirs.append(gui_resources_dir) + pass + else: + 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] = os.pathsep.join(dirs) dirs.reverse() # reverse order, like in "path" variable - FILO-style processing 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 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable - for dir in dirs: - filename = os.path.join(dir, appname+'.xml') + for directory in dirs: + filename = os.path.join(directory, appname + '.xml') if not os.path.exists(filename): - if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename + if verbose(): print("Configure parser: Warning : can not find configuration file %s" % filename) else: try: p = xml_parser(filename, _opts, []) _opts = p.opts - except: - if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename + except Exception: + if verbose(): print("Configure parser: Error : can not read configuration file %s" % filename) pass # parse user configuration file @@ -987,33 +937,33 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn user_config = cmd_opts.resources if not user_config: user_config = userFile(appname, cfgname) - if verbose(): print "Configure parser: user configuration file is", user_config + if verbose(): print("Configure parser: user configuration file is", user_config) if not user_config or not os.path.exists(user_config): - if verbose(): print "Configure parser: Warning : can not find user configuration file" + if verbose(): print("Configure parser: Warning : can not find user configuration file") else: try: p = xml_parser(user_config, _opts, []) _opts = p.opts - except: - if verbose(): print 'Configure parser: Error : can not read user configuration file' + except Exception: + if verbose(): print('Configure parser: Error : can not read user configuration file') user_config = "" args = _opts args['user_config'] = user_config - #print "User Configuration file: ", args['user_config'] + # print("User Configuration file: ", args['user_config']) # set default values for options which are NOT set in config files for aKey in listKeys: - if not args.has_key( aKey ): + if aKey not in args: args[aKey] = [] for aKey in boolKeys: - if not args.has_key( aKey ): + if aKey not in args: args[aKey] = 0 if args[file_nam]: - afile=args[file_nam] + afile = args[file_nam] args[file_nam] = [afile] args[appname_nam] = appname @@ -1041,7 +991,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn if cmd_opts.batch is not None: args[batch_nam] = True - if not gui_available: + if not os.getenv("GUI_ROOT_DIR") or not os.path.isdir(os.getenv("GUI_ROOT_DIR")): args[gui_nam] = False if args[gui_nam]: @@ -1065,26 +1015,28 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn # Naming Service port log file if cmd_opts.ns_port_log_file is not None: - args["ns_port_log_file"] = cmd_opts.ns_port_log_file + args["ns_port_log_file"] = cmd_opts.ns_port_log_file # Study files - for arg in cmd_args: - if arg[-4:] == ".hdf" and not args["study_hdf"]: + for arg in cmd_opts.arguments: + file_extension = os.path.splitext(arg)[-1] + if file_extension == ".hdf" and not args["study_hdf"]: args["study_hdf"] = arg # Python scripts - args[script_nam] = getScriptsAndArgs(cmd_args) - new_args = [] + from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs + args[script_nam] = getScriptsAndArgs(cmd_opts.arguments) if args[gui_nam] and args["session_gui"]: - from salomeContextUtils import ScriptAndArgs - for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects - script = re.sub(r'^python.*\s+', r'', sa_obj.script) + new_args = [] + for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects + script = re.sub(r'^python. *\s+', r'', sa_obj.script) new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out)) # args[script_nam] = new_args # xterm - if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm + if cmd_opts.xterm is not None: + args[xterm_nam] = cmd_opts.xterm # Modules if cmd_opts.modules is not None: @@ -1101,11 +1053,11 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn # Embedded if cmd_opts.embedded is not None: - args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) ) + args[embedded_nam] = [a for a in re.split( "[:;,]", cmd_opts.embedded ) if a.strip()] # Standalone if cmd_opts.standalone is not None: - args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) ) + args[standalone_nam] = [a for a in re.split( "[:;,]", cmd_opts.standalone ) if a.strip()] # Normalize the '--standalone' and '--embedded' parameters standalone, embedded = process_containers_params( args.get( standalone_nam ), @@ -1154,6 +1106,14 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn args[shutdown_servers_nam] = cmd_opts.shutdown_servers pass + # Launcher only + if cmd_opts.launcher_only is not None: + args[launcher_only_nam] = cmd_opts.launcher_only + + # machine and port where is the Launcher + if cmd_opts.launcher is not None: + args[launcher_nam] = cmd_opts.launcher + # Foreground if cmd_opts.foreground is None: args[foreground_nam] = 1 @@ -1165,23 +1125,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn if cmd_opts.wake_up_session is not None: args[wake_up_session_nam] = cmd_opts.wake_up_session - # siman options - if cmd_opts.siman is not None: - args[siman_nam] = cmd_opts.siman - if cmd_opts.siman_study is not None: - args[siman_study_nam] = cmd_opts.siman_study - if cmd_opts.siman_scenario is not None: - args[siman_scenario_nam] = cmd_opts.siman_scenario - if cmd_opts.siman_user is not None: - args[siman_user_nam] = cmd_opts.siman_user - - #################################################### - # Add values to args - for add_opt in theAdditionalOptions: - cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest) - exec(cmd) - #################################################### - # disable signals handling if args[except_nam] == 1: os.environ["NOT_INTERCEPT_SIGNALS"] = "1" @@ -1204,7 +1147,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn 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] + # print("* '"+m+"' should be deleted from ",args[modules_nam]) pass # Test @@ -1227,12 +1170,21 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn if cmd_opts.use_port is not None: min_port = 2810 max_port = min_port + 100 - if cmd_opts.use_port not in xrange(min_port, max_port+1): - print "Error: port number should be in range [%d, %d])" % (min_port, max_port) + if cmd_opts.use_port not in range(min_port, max_port+1): + print("Error: port number should be in range [%d, %d])" % (min_port, max_port)) sys.exit(1) args[useport_nam] = cmd_opts.use_port + if cmd_opts.language is not None: + langs = args["language_languages"] if "language_languages" in args else [] + if cmd_opts.language not in langs: + print("Error: unsupported language: %s" % cmd_opts.language) + sys.exit(1) + args[lang_nam] = cmd_opts.language + # return arguments - os.environ[config_var] = os.pathsep.join(dirs) - #print "Args: ", args + if not keepEnvironment: + os.environ[config_var] = os.pathsep.join(dirs) + + # print("Args: ", args) return args