1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
4 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License.
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 import os, glob, string, sys, re
29 from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir
31 from salomeLauncherUtils import getScriptsAndArgs
33 # names of tags in XML configuration file
39 # names of attributes in XML configuration file
43 # certain values in XML configuration file ("launch" section)
51 portkill_nam = "portkill"
52 killall_nam = "killall"
53 modules_nam = "modules"
54 embedded_nam = "embedded"
55 standalone_nam = "standalone"
57 terminal_nam = "terminal"
59 except_nam = "noexcepthandler"
60 terminal_nam = "terminal"
65 gdb_session_nam = "gdb_session"
66 ddd_session_nam = "ddd_session"
67 valgrind_session_nam = "valgrind_session"
68 shutdown_servers_nam = "shutdown_servers"
69 foreground_nam = "foreground"
70 wake_up_session_nam = "wake_up_session"
72 # values in XML configuration file giving specific module parameters (<module_name> section)
73 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
74 plugins_nam = "plugins"
76 # values passed as arguments, NOT read from XML config file, but set from within this script
77 appname_nam = "appname"
79 useport_nam = "useport"
80 salomecfgname = "salome"
81 salomeappname = "SalomeApp"
82 script_nam = "pyscript"
84 # possible choices for the "embedded" and "standalone" parameters
85 embedded_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
86 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"]
88 # values of boolean type (must be '0' or '1').
89 # xml_parser.boolValue() is used for correct setting
90 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
91 intKeys = ( interp_nam, )
94 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
97 # Get the application version
98 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
103 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
104 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
105 filename = root_dir + "/bin/salome/VERSION"
106 root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found
107 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
108 filename = root_dir + "/bin/salome/VERSION"
110 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
111 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
113 return match.group( 1 )
119 # Calculate and return configuration file unique ID
120 # For example: for SALOME version 3.1.0a1 the id is 300999701
122 def version_id(fname):
123 major = minor = release = dev1 = dev2 = 0
124 vers = fname.split(".")
125 if len(vers) > 0: major = int(vers[0])
126 if len(vers) > 1: minor = int(vers[1])
128 mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I)
130 release = int(mr.group(1))
132 tag = mr.group(2).strip().lower()
134 dev1 = 49 # release candidate
136 dev1 = ord(tag)-ord('a')+1
139 dev2 = int(mr.group(3).strip())
142 dev = dev1 * 100 + dev2
144 ver = ver * 100 + minor
145 ver = ver * 100 + release
147 if dev > 0: ver = ver - dev
151 # Get default user configuration file name
153 # - on Linux: ~/.config/salome/SalomeApprc[.<version>]
154 # - on Windows: ~/SalomeApp.xml[.<version>]
155 # where <version> is an optional version number
157 def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
160 if sys.platform == "win32":
161 filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v))
164 filename = os.path.join(getHomeDir(), ".config", cfgname, "%src%s" % (appname, v))
167 filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v))
173 # Get user configuration file name
175 def userFile(appname, cfgname):
178 if not v: return None # unknown version
180 # get default user file name
181 filename = defaultUserFile(appname, cfgname)
182 if not filename: return None # default user file name is bad
184 # check that default user file exists
185 if os.path.exists(filename): return filename # user file is found
187 # otherwise try to detect any appropriate user file
189 # ... calculate default version id
191 if not id0: return None # bad version id -> can't detect appropriate file
193 # ... get all existing user preferences files
194 if sys.platform == "win32":
195 files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname))
199 # Since v6.6.0 - in ~/.config/salome directory, without dot prefix
200 files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "%src.*" % appname))
201 # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility)
202 files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname))
204 # old style (before v6.5.0) - in ~ directory, dot-prefixed
205 files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname))
208 # ... loop through all files and find most appopriate file (with closest id)
212 ff = os.path.basename( f )
213 if sys.platform == "win32":
214 match = re.search( r'^%s\.xml\.([a-zA-Z0-9.]+)$'%appname, ff )
216 match = re.search( r'^\.?%src\.([a-zA-Z0-9.]+)$'%appname, ff )
218 ver = version_id(match.group(1))
219 if not ver: continue # bad version id -> skip file
220 if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
224 elif abs(appr_id-id0) == abs(ver-id0):
225 if not os.path.basename(f).startswith("."): appr_file = f
233 def process_containers_params( standalone, embedded ):
234 # 1. filter inappropriate containers names
235 if standalone is not None:
236 standalone = filter( lambda x: x in standalone_choices, standalone )
237 if embedded is not None:
238 embedded = filter( lambda x: x in embedded_choices, embedded )
240 # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
241 # parameter --> i.e. 'standalone' parameter has higher priority
242 if standalone is not None and embedded is not None:
243 embedded = filter( lambda x: x not in standalone, embedded )
245 # 3. return corrected parameters values
246 return standalone, embedded
248 # -----------------------------------------------------------------------------
251 # XML reader for launch configuration file usage
257 def __init__(self, fileName, _opts, _importHistory):
258 #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
259 if verbose(): print "Configure parser: processing %s ..." % fileName
260 self.fileName = os.path.abspath(fileName)
261 self.importHistory = _importHistory
262 self.importHistory.append(self.fileName)
265 self.section = section_to_skip
266 parser = xml.sax.make_parser()
267 parser.setContentHandler(self)
268 parser.parse(fileName)
269 standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
270 self.opts.get( embedded_nam ) )
271 if standalone is not None:
272 self.opts[ standalone_nam ] = standalone
273 if embedded is not None:
274 self.opts[ embedded_nam ] = embedded
277 def boolValue( self, str ):
279 if isinstance(strloc, types.UnicodeType):
280 strloc = strloc.encode().strip()
281 if isinstance(strloc, types.StringType):
282 strlow = strloc.lower()
283 if strlow in ("1", "yes", "y", "on", "true", "ok"):
285 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
290 def intValue( self, str ):
292 if isinstance(strloc, types.UnicodeType):
293 strloc = strloc.encode().strip()
294 if isinstance(strloc, types.StringType):
295 strlow = strloc.lower()
296 if strlow in ("1", "yes", "y", "on", "true", "ok"):
298 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
301 return string.atoi(strloc)
305 def startElement(self, name, attrs):
306 self.space.append(name)
309 # if we are importing file
310 if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
311 self.importFile( attrs.getValue(nam_att) )
313 # if we are analyzing "section" element and its "name" attribute is
314 # either "launch" or module name -- set section_name
315 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
316 section_name = attrs.getValue( nam_att )
317 if section_name == lanch_nam:
318 self.section = section_name # launch section
319 elif self.opts.has_key( modules_nam ) and \
320 section_name in self.opts[ modules_nam ]:
321 self.section = section_name # <module> section
323 self.section = section_to_skip # any other section
326 # if we are analyzing "parameter" elements - children of either
327 # "section launch" or "section "<module>"" element, then store them
328 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
329 elif self.section != section_to_skip and \
330 self.space == [doc_tag, sec_tag, par_tag] and \
331 nam_att in attrs.getNames() and \
332 val_att in attrs.getNames():
333 nam = attrs.getValue( nam_att )
334 val = attrs.getValue( val_att )
335 if self.section == lanch_nam: # key for launch section
337 else: # key for <module> section
338 key = self.section + "_" + nam
340 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
342 self.opts[key] = self.intValue( val ) # assign integer value
343 elif nam in listKeys:
344 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
350 def endElement(self, name):
353 if self.section != section_to_skip and name == sec_tag:
354 self.section = section_to_skip
357 def characters(self, content):
360 def processingInstruction(self, target, data):
363 def setDocumentLocator(self, locator):
366 def startDocument(self):
370 def endDocument(self):
374 def importFile(self, fname):
376 if os.path.isabs (fname) :
379 absfname = os.path.join(os.path.dirname(self.fileName), fname)
381 # check existing and registry file
382 for ext in ["", ".xml", ".XML"] :
383 if os.path.exists(absfname + ext) :
385 if absfname in self.importHistory :
386 if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
387 return # already imported
391 if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
396 # copy current options
398 opts = copy.deepcopy(self.opts)
400 imp = xml_parser(absfname, opts, self.importHistory)
402 for key in imp.opts.keys():
403 if not self.opts.has_key(key):
404 self.opts[key] = imp.opts[key]
409 if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
413 # -----------------------------------------------------------------------------
415 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
416 '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
418 boolean_choices = booleans.keys()
420 def check_embedded(option, opt, value, parser):
421 from optparse import OptionValueError
422 assert value is not None
423 if parser.values.embedded:
424 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
427 if parser.values.standalone:
428 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
431 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
433 if v not in embedded_choices:
434 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
435 if v not in embedded:
438 del standalone[ standalone.index( v ) ]
440 parser.values.embedded = ",".join( embedded )
441 parser.values.standalone = ",".join( standalone )
444 def check_standalone(option, opt, value, parser):
445 from optparse import OptionValueError
446 assert value is not None
447 if parser.values.embedded:
448 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
451 if parser.values.standalone:
452 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
455 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
457 if v not in standalone_choices:
458 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
459 if v not in standalone:
460 standalone.append( v )
462 del embedded[ embedded.index( v ) ]
464 parser.values.embedded = ",".join( embedded )
465 parser.values.standalone = ",".join( standalone )
468 def store_boolean (option, opt, value, parser, *args):
469 if isinstance(value, types.StringType):
471 value_conv = booleans[value.strip().lower()]
472 for attribute in args:
473 setattr(parser.values, attribute, value_conv)
475 raise optparse.OptionValueError(
476 "option %s: invalid boolean value: %s (choose from %s)"
477 % (opt, value, boolean_choices))
479 for attribute in args:
480 setattr(parser.values, attribute, value)
482 def CreateOptionParser (theAdditionalOptions=[]):
483 # GUI/Terminal. Default: GUI
484 help_str = "Launch without GUI (in the terminal mode)."
485 o_t = optparse.Option("-t",
487 action="store_false",
491 help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
492 o_b = optparse.Option("-b",
498 help_str = "Launch in GUI mode [default]."
499 o_g = optparse.Option("-g",
505 # Show Desktop (inly in GUI mode). Default: True
506 help_str = "1 to activate GUI desktop [default], "
507 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
508 help_str += "Ignored in the terminal mode."
509 o_d = optparse.Option("-d",
512 #type="choice", choices=boolean_choices,
514 action="callback", callback=store_boolean, callback_args=('desktop',),
517 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
518 help_str += "The same as --show-desktop=0."
519 o_o = optparse.Option("-o",
521 action="store_false",
525 # Use logger or log-file. Default: nothing.
526 help_str = "Redirect messages to the CORBA collector."
527 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
528 o_l = optparse.Option("-l",
530 action="store_const", const="CORBA",
533 help_str = "Redirect messages to the <log-file>"
534 o_f = optparse.Option("-f",
536 metavar="<log-file>",
542 # Configuration XML file. Default: see defaultUserFile() function
543 help_str = "Parse application settings from the <file> "
544 help_str += "instead of default %s" % defaultUserFile()
545 o_r = optparse.Option("-r",
553 # Use own xterm for each server. Default: False.
554 help_str = "Launch each SALOME server in own xterm console"
555 o_x = optparse.Option("-x",
561 # Modules. Default: Like in configuration files.
562 help_str = "SALOME modules list (where <module1>, <module2> are the names "
563 help_str += "of SALOME modules which should be available in the SALOME session)"
564 o_m = optparse.Option("-m",
566 metavar="<module1,module2,...>",
572 # Embedded servers. Default: Like in configuration files.
573 help_str = "CORBA servers to be launched in the Session embedded mode. "
574 help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
575 help_str += "[by default the value from the configuration files is used]"
576 o_e = optparse.Option("-e",
578 metavar="<server1,server2,...>",
582 callback=check_embedded,
585 # Standalone servers. Default: Like in configuration files.
586 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
587 help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
588 help_str += "[by default the value from the configuration files is used]"
589 o_s = optparse.Option("-s",
591 metavar="<server1,server2,...>",
595 callback=check_standalone,
598 # Kill with port. Default: False.
599 help_str = "Kill SALOME with the current port"
600 o_p = optparse.Option("-p",
606 # Kill all. Default: False.
607 help_str = "Kill all running SALOME sessions"
608 o_k = optparse.Option("-k",
614 # Additional python interpreters. Default: 0.
615 help_str = "The number of additional external python interpreters to run. "
616 help_str += "Each additional python interpreter is run in separate "
617 help_str += "xterm session with properly set SALOME environment"
618 o_i = optparse.Option("-i",
626 # Splash. Default: True.
627 help_str = "1 to display splash screen [default], "
628 help_str += "0 to disable splash screen. "
629 help_str += "This option is ignored in the terminal mode. "
630 help_str += "It is also ignored if --show-desktop=0 option is used."
631 o_z = optparse.Option("-z",
634 #type="choice", choices=boolean_choices,
636 action="callback", callback=store_boolean, callback_args=('splash',),
640 # Catch exceptions. Default: True.
641 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
642 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
643 o_c = optparse.Option("-c",
644 "--catch-exceptions",
646 #type="choice", choices=boolean_choices,
648 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
649 dest="catch_exceptions",
652 # Print free port and exit
653 help_str = "Print free port and exit"
654 o_a = optparse.Option("--print-port",
656 dest="print_port", default=False,
659 # Do not relink ${HOME}/.omniORB_last.cfg
660 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
661 o_n = optparse.Option("--nosave-config",
662 action="store_false",
663 dest="save_config", default=True,
666 # Launch with interactive python console. Default: False.
667 help_str = "Launch with interactive python console."
668 o_pi = optparse.Option("--pinter",
673 # Print Naming service port into a user file. Default: False.
674 help_str = "Print Naming Service Port into a user file."
675 o_nspl = optparse.Option("--ns-port-log",
676 metavar="<ns_port_log_file>",
679 dest="ns_port_log_file",
682 # Write/read test script file with help of TestRecorder. Default: False.
683 help_str = "Write/read test script file with help of TestRecorder."
684 o_test = optparse.Option("--test",
685 metavar="<test_script_file>",
688 dest="test_script_file",
691 # Reproducing test script with help of TestRecorder. Default: False.
692 help_str = "Reproducing test script with help of TestRecorder."
693 o_play = optparse.Option("--play",
694 metavar="<play_script_file>",
697 dest="play_script_file",
701 help_str = "Launch session with gdb"
702 o_gdb = optparse.Option("--gdb-session",
704 dest="gdb_session", default=False,
708 help_str = "Launch session with ddd"
709 o_ddd = optparse.Option("--ddd-session",
711 dest="ddd_session", default=False,
716 help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
717 o_valgrind = optparse.Option("--valgrind-session",
719 dest="valgrind_session", default=False,
722 # shutdown-servers. Default: False.
723 help_str = "1 to shutdown standalone servers when leaving python interpreter, "
724 help_str += "0 to keep the standalone servers as daemon [default]. "
725 help_str += "This option is only useful in batchmode "
726 help_str += "(terminal mode or without showing desktop)."
727 o_shutdown = optparse.Option("--shutdown-servers",
729 #type="choice", choices=boolean_choices,
731 action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
732 dest="shutdown_servers",
735 # foreground. Default: True.
736 help_str = "0 and runSalome exits after have launched the gui, "
737 help_str += "1 to launch runSalome in foreground mode [default]."
738 o_foreground = optparse.Option("--foreground",
740 #type="choice", choices=boolean_choices,
742 action="callback", callback=store_boolean, callback_args=('foreground',),
747 help_str = "Wake up a previously closed session. "
748 help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
749 help_str += "If this variable is not setted, the last configuration is taken. "
750 o_wake_up = optparse.Option("--wake-up-session",
752 dest="wake_up_session", default=False,
756 help_str = "Mode used to launch server processes (daemon or fork)."
757 o_slm = optparse.Option("--server-launch-mode",
758 metavar="<server_launch_mode>",
760 choices=["daemon","fork"],
762 dest="server_launch_mode",
766 help_str = "Preferable port SALOME to be started on. "
767 help_str += "If specified port is not busy, SALOME session will start on it; "
768 help_str += "otherwise, any available port will be searched and used."
769 o_port = optparse.Option("--port",
777 opt_list = [o_t,o_g, # GUI/Terminal
780 o_l,o_f, # Use logger or log-file
781 o_r, # Configuration XML file
784 o_e, # Embedded servers
785 o_s, # Standalone servers
786 o_p, # Kill with port
788 o_i, # Additional python interpreters
790 o_c, # Catch exceptions
791 o_a, # Print free port and exit
792 o_n, # --nosave-config
793 o_pi, # Interactive python console
795 o_test, # Write/read test script file with help of TestRecorder
796 o_play, # Reproducing test script with help of TestRecorder
803 o_slm, # Server launch mode
807 #std_options = ["gui", "desktop", "log_file", "resources",
808 # "xterm", "modules", "embedded", "standalone",
809 # "portkill", "killall", "interp", "splash",
810 # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
812 opt_list += theAdditionalOptions
814 a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
815 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,...
817 version_str = "Salome %s" % version()
818 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
822 # -----------------------------------------------------------------------------
825 # Get the environment
828 # this attribute is obsolete
832 def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
834 # Collect launch configuration files:
835 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
836 # define a list of directories (separated by ':' or ';' symbol) is checked
837 # - If the environment variable "<appname>Config" is not set, only
838 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
839 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
840 # so it is not necessary to put it in the "<appname>Config" variable
841 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
842 # (SalomeApp.xml) which define SALOME configuration
843 # - These directories are analyzed beginning from the last one in the list,
844 # so the first directory listed in "<appname>Config" environment variable
845 # has higher priority: it means that if some configuration options
846 # is found in the next analyzed cofiguration file - it will be replaced
847 # - The last configuration file which is parsed is user configuration file
848 # situated in the home directory (if it exists):
849 # * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
850 # * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
851 # - Command line options have the highest priority and replace options
852 # specified in configuration file(s)
856 config_var = appname+'Config'
859 if os.sys.platform == 'win32':
862 # check KERNEL_ROOT_DIR
864 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
867 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
868 KERNEL_ROOT_DIR is mandatory.
873 ############################
874 # parse command line options
875 pars = CreateOptionParser(theAdditionalOptions)
876 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
877 ############################
879 # Process --print-port option
880 if cmd_opts.print_port:
882 PortManager.start_server(nbSimultaneous=25, timeout=10)
883 from searchFreePort import searchFreePort
885 print "port:%s"%(os.environ['NSPORT'])
889 # set resources variable SalomeAppConfig if it is not set yet
891 if os.getenv(config_var):
892 if sys.platform == 'win32':
893 dirs += re.split(';', os.getenv(config_var))
895 dirs += re.split('[;|:]', os.getenv(config_var))
898 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
899 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
902 gui_available = False
903 if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
904 dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
906 os.environ[config_var] = separator.join(dirs)
908 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
911 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
915 _opts = {} # associative array of options to be filled
917 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
919 filename = os.path.join(dir, appname+'.xml')
920 if not os.path.exists(filename):
921 if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
924 p = xml_parser(filename, _opts, [])
927 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
930 # parse user configuration file
931 # It can be set via --resources=<file> command line option
932 # or is given from default location (see defaultUserFile() function)
933 # If user file for the current version is not found the nearest to it is used
934 user_config = cmd_opts.resources
936 user_config = userFile(appname, cfgname)
937 if verbose(): print "Configure parser: user configuration file is", user_config
938 if not user_config or not os.path.exists(user_config):
939 if verbose(): print "Configure parser: Warning : can not find user configuration file"
942 p = xml_parser(user_config, _opts, [])
945 if verbose(): print 'Configure parser: Error : can not read user configuration file'
950 args['user_config'] = user_config
951 #print "User Configuration file: ", args['user_config']
953 # set default values for options which are NOT set in config files
954 for aKey in listKeys:
955 if not args.has_key( aKey ):
958 for aKey in boolKeys:
959 if not args.has_key( aKey ):
964 args[file_nam]=[afile]
966 args[appname_nam] = appname
968 # get the port number
969 my_port = getPortNumber()
971 args[port_nam] = my_port
973 ####################################################
974 # apply command-line options to the arguments
975 # each option given in command line overrides the option from xml config file
977 # Options: gui, desktop, log_file, resources,
978 # xterm, modules, embedded, standalone,
979 # portkill, killall, interp, splash,
980 # catch_exceptions, pinter
982 # GUI/Terminal, Desktop, Splash, STUDY_HDF
983 args["session_gui"] = False
984 args[batch_nam] = False
985 args["study_hdf"] = None
986 if cmd_opts.gui is not None:
987 args[gui_nam] = cmd_opts.gui
988 if cmd_opts.batch is not None:
989 args[batch_nam] = True
991 if not gui_available:
992 args[gui_nam] = False
995 args["session_gui"] = True
996 if cmd_opts.desktop is not None:
997 args["session_gui"] = cmd_opts.desktop
998 args[splash_nam] = cmd_opts.desktop
999 if args["session_gui"]:
1000 if cmd_opts.splash is not None:
1001 args[splash_nam] = cmd_opts.splash
1003 args["session_gui"] = False
1004 args[splash_nam] = False
1007 if cmd_opts.log_file is not None:
1008 if cmd_opts.log_file == 'CORBA':
1009 args[logger_nam] = True
1011 args[file_nam] = [cmd_opts.log_file]
1013 # Naming Service port log file
1014 if cmd_opts.ns_port_log_file is not None:
1015 args["ns_port_log_file"] = cmd_opts.ns_port_log_file
1018 for arg in cmd_args:
1019 if arg[-4:] == ".hdf" and not args["study_hdf"]:
1020 args["study_hdf"] = arg
1023 args[script_nam] = getScriptsAndArgs(cmd_args)
1026 for d in args[script_nam]:
1027 for s, a in d.items():
1028 v = re.sub(r'^python.*\s+', r'', s)
1029 new_args.append({v:a})
1031 args[script_nam] = new_args
1034 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1037 if cmd_opts.modules is not None:
1038 args[modules_nam] = []
1039 listlist = cmd_opts.modules
1040 for listi in listlist:
1041 args[modules_nam] += re.split( "[:;,]", listi)
1043 # if --modules (-m) command line option is not given
1044 # try SALOME_MODULES environment variable
1045 if os.getenv( "SALOME_MODULES" ):
1046 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1050 if cmd_opts.embedded is not None:
1051 args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1054 if cmd_opts.standalone is not None:
1055 args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1057 # Normalize the '--standalone' and '--embedded' parameters
1058 standalone, embedded = process_containers_params( args.get( standalone_nam ),
1059 args.get( embedded_nam ) )
1060 if standalone is not None:
1061 args[ standalone_nam ] = standalone
1062 if embedded is not None:
1063 args[ embedded_nam ] = embedded
1066 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1067 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
1070 if cmd_opts.interp is not None:
1071 args[interp_nam] = cmd_opts.interp
1074 if cmd_opts.catch_exceptions is not None:
1075 args[except_nam] = not cmd_opts.catch_exceptions
1077 # Relink config file
1078 if cmd_opts.save_config is not None:
1079 args['save_config'] = cmd_opts.save_config
1081 # Interactive python console
1082 if cmd_opts.pinter is not None:
1083 args[pinter_nam] = cmd_opts.pinter
1085 # Gdb session in xterm
1086 if cmd_opts.gdb_session is not None:
1087 args[gdb_session_nam] = cmd_opts.gdb_session
1089 # Ddd session in xterm
1090 if cmd_opts.ddd_session is not None:
1091 args[ddd_session_nam] = cmd_opts.ddd_session
1094 if cmd_opts.valgrind_session is not None:
1095 args[valgrind_session_nam] = cmd_opts.valgrind_session
1098 if cmd_opts.shutdown_servers is None:
1099 args[shutdown_servers_nam] = 0
1101 args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1105 if cmd_opts.foreground is None:
1106 args[foreground_nam] = 1
1108 args[foreground_nam] = cmd_opts.foreground
1112 if cmd_opts.wake_up_session is not None:
1113 args[wake_up_session_nam] = cmd_opts.wake_up_session
1115 ####################################################
1116 # Add <theAdditionalOptions> values to args
1117 for add_opt in theAdditionalOptions:
1118 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
1120 ####################################################
1122 # disable signals handling
1123 if args[except_nam] == 1:
1124 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1127 # now modify SalomeAppConfig environment variable
1128 # to take into account the SALOME modules
1129 if os.sys.platform == 'win32':
1130 dirs = re.split('[;]', os.environ[config_var] )
1132 dirs = re.split('[;|:]', os.environ[config_var] )
1133 for m in args[modules_nam]:
1134 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
1135 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
1136 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
1137 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1138 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
1140 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1141 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
1144 #print "* '"+m+"' should be deleted from ",args[modules_nam]
1148 if cmd_opts.test_script_file is not None:
1150 filename = cmd_opts.test_script_file
1151 args[test_nam] += re.split( "[:;,]", filename )
1154 if cmd_opts.play_script_file is not None:
1156 filename = cmd_opts.play_script_file
1157 args[play_nam] += re.split( "[:;,]", filename )
1159 # Server launch command
1160 if cmd_opts.server_launch_mode is not None:
1161 args["server_launch_mode"] = cmd_opts.server_launch_mode
1163 # Server launch command
1164 if cmd_opts.use_port is not None:
1166 max_port = min_port + 100
1167 if cmd_opts.use_port not in xrange(min_port, max_port+1):
1168 print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
1170 args[useport_nam] = cmd_opts.use_port
1173 os.environ[config_var] = separator.join(dirs)
1174 #print "Args: ", args