1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2011 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 # names of tags in XML configuration file
37 # names of attributes in XML configuration file
41 # certain values in XML configuration file ("launch" section)
49 portkill_nam = "portkill"
50 killall_nam = "killall"
51 modules_nam = "modules"
52 embedded_nam = "embedded"
53 standalone_nam = "standalone"
55 terminal_nam = "terminal"
57 except_nam = "noexcepthandler"
58 terminal_nam = "terminal"
63 gdb_session_nam = "gdb_session"
64 ddd_session_nam = "ddd_session"
65 valgrind_session_nam = "valgrind_session"
66 shutdown_servers_nam = "shutdown_servers"
67 foreground_nam = "foreground"
68 wake_up_session_nam = "wake_up_session"
70 # values in XML configuration file giving specific module parameters (<module_name> section)
71 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
72 plugins_nam = "plugins"
74 # values passed as arguments, NOT read from XML config file, but set from within this script
75 appname_nam = "appname"
77 salomecfgname = "salome"
78 salomeappname = "SalomeApp"
79 script_nam = "pyscript"
81 # possible choices for the "embedded" and "standalone" parameters
82 embedded_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
83 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "pyContainer"]
85 # values of boolean type (must be '0' or '1').
86 # xml_parser.boolValue() is used for correct setting
87 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
88 intKeys = ( interp_nam, )
91 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
94 # Get the application version
95 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
100 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
101 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
102 filename = root_dir + "/bin/salome/VERSION"
103 root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found
104 if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
105 filename = root_dir + "/bin/salome/VERSION"
107 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
108 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
110 return match.group( 1 )
116 # Calculate and return configuration file unique ID
117 # For example: for SALOME version 3.1.0a1 the id is 300999701
119 def version_id(fname):
120 major = minor = release = dev1 = dev2 = 0
121 vers = fname.split(".")
122 if len(vers) > 0: major = int(vers[0])
123 if len(vers) > 1: minor = int(vers[1])
125 mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
127 release = int(mr.group(1))
128 if mr.group(2).strip(): dev1 = ord(mr.group(2).strip())
129 if mr.group(3).strip(): dev2 = int(mr.group(3).strip())
132 dev = dev1 * 100 + dev2
134 ver = ver * 100 + minor
135 ver = ver * 100 + release
137 if dev > 0: ver = ver - 10000 + dev
141 # Get default user configuration file name
143 # - on Linux: ~/.config/salome/.SalomeApprc.[version]
144 # - on Windows: ~/SalomeApp.xml.[version]
145 # where [version] is a version number
147 def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
150 if sys.platform == "win32":
151 filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v))
154 filename = os.path.join(getHomeDir(), ".config", cfgname, ".%src%s" % (appname, v))
157 filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v))
163 # Get user configuration file name
165 def userFile(appname, cfgname):
168 if not v: return None # unknown version
170 # get default user file name
171 filename = defaultUserFile(appname, cfgname)
172 if not filename: return None # default user file name is bad
174 # check that default user file exists
175 if os.path.exists(filename): return filename # user file is found
177 # otherwise try to detect any appropriate user file
179 # ... calculate default version id
181 if not id0: return None # bad version id -> can't detect appropriate file
183 # ... get all existing user preferences files
184 if sys.platform == "win32":
185 files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname))
188 if cfgname: files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname))
189 files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname))
192 # ... loop through all files and find most appopriate file (with closest id)
196 if sys.platform == "win32":
197 match = re.search( r'%s\.xml\.([a-zA-Z0-9.]+)$'%appname, f )
199 match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, f )
201 ver = version_id(match.group(1))
202 if not ver: continue # bad version id -> skip file
203 if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
213 def process_containers_params( standalone, embedded ):
214 # 1. filter inappropriate containers names
215 if standalone is not None:
216 standalone = filter( lambda x: x in standalone_choices, standalone )
217 if embedded is not None:
218 embedded = filter( lambda x: x in embedded_choices, embedded )
220 # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
221 # parameter --> i.e. 'standalone' parameter has higher priority
222 if standalone is not None and embedded is not None:
223 embedded = filter( lambda x: x not in standalone, embedded )
225 # 3. return corrected parameters values
226 return standalone, embedded
228 # -----------------------------------------------------------------------------
231 # XML reader for launch configuration file usage
237 def __init__(self, fileName, _opts, _importHistory=[] ):
238 if verbose(): print "Configure parser: processing %s ..." % fileName
239 self.fileName = os.path.abspath(fileName)
240 self.importHistory = _importHistory
241 self.importHistory.append(self.fileName)
244 self.section = section_to_skip
245 parser = xml.sax.make_parser()
246 parser.setContentHandler(self)
247 parser.parse(fileName)
248 standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
249 self.opts.get( embedded_nam ) )
250 if standalone is not None:
251 self.opts[ standalone_nam ] = standalone
252 if embedded is not None:
253 self.opts[ embedded_nam ] = embedded
256 def boolValue( self, str ):
258 if isinstance(strloc, types.UnicodeType):
259 strloc = strloc.encode().strip()
260 if isinstance(strloc, types.StringType):
261 strlow = strloc.lower()
262 if strlow in ("1", "yes", "y", "on", "true", "ok"):
264 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
269 def intValue( self, str ):
271 if isinstance(strloc, types.UnicodeType):
272 strloc = strloc.encode().strip()
273 if isinstance(strloc, types.StringType):
274 strlow = strloc.lower()
275 if strlow in ("1", "yes", "y", "on", "true", "ok"):
277 elif strlow in ("0", "no", "n", "off", "false", "cancel"):
280 return string.atoi(strloc)
284 def startElement(self, name, attrs):
285 self.space.append(name)
288 # if we are importing file
289 if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
290 self.importFile( attrs.getValue(nam_att) )
292 # if we are analyzing "section" element and its "name" attribute is
293 # either "launch" or module name -- set section_name
294 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
295 section_name = attrs.getValue( nam_att )
296 if section_name == lanch_nam:
297 self.section = section_name # launch section
298 elif self.opts.has_key( modules_nam ) and \
299 section_name in self.opts[ modules_nam ]:
300 self.section = section_name # <module> section
302 self.section = section_to_skip # any other section
305 # if we are analyzing "parameter" elements - children of either
306 # "section launch" or "section "<module>"" element, then store them
307 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
308 elif self.section != section_to_skip and \
309 self.space == [doc_tag, sec_tag, par_tag] and \
310 nam_att in attrs.getNames() and \
311 val_att in attrs.getNames():
312 nam = attrs.getValue( nam_att )
313 val = attrs.getValue( val_att )
314 if self.section == lanch_nam: # key for launch section
316 else: # key for <module> section
317 key = self.section + "_" + nam
319 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
321 self.opts[key] = self.intValue( val ) # assign integer value
322 elif nam in listKeys:
323 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
329 def endElement(self, name):
332 if self.section != section_to_skip and name == sec_tag:
333 self.section = section_to_skip
336 def characters(self, content):
339 def processingInstruction(self, target, data):
342 def setDocumentLocator(self, locator):
345 def startDocument(self):
349 def endDocument(self):
353 def importFile(self, fname):
355 if os.path.isabs (fname) :
358 absfname = os.path.join(os.path.dirname(self.fileName), fname)
360 # check existing and registry file
361 for ext in ["", ".xml", ".XML"] :
362 if os.path.exists(absfname + ext) :
364 if absfname in self.importHistory :
365 if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
366 return # already imported
370 if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
375 # copy current options
377 opts = copy.deepcopy(self.opts)
379 imp = xml_parser(absfname, opts, self.importHistory)
381 for key in imp.opts.keys():
382 if not self.opts.has_key(key):
383 self.opts[key] = imp.opts[key]
388 if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
392 # -----------------------------------------------------------------------------
394 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
395 '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
397 boolean_choices = booleans.keys()
399 def check_embedded(option, opt, value, parser):
400 from optparse import OptionValueError
401 assert value is not None
402 if parser.values.embedded:
403 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
406 if parser.values.standalone:
407 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
410 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
412 if v not in embedded_choices:
413 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
414 if v not in embedded:
417 del standalone[ standalone.index( v ) ]
419 parser.values.embedded = ",".join( embedded )
420 parser.values.standalone = ",".join( standalone )
423 def check_standalone(option, opt, value, parser):
424 from optparse import OptionValueError
425 assert value is not None
426 if parser.values.embedded:
427 embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
430 if parser.values.standalone:
431 standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
434 vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
436 if v not in standalone_choices:
437 raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
438 if v not in standalone:
439 standalone.append( v )
441 del embedded[ embedded.index( v ) ]
443 parser.values.embedded = ",".join( embedded )
444 parser.values.standalone = ",".join( standalone )
447 def store_boolean (option, opt, value, parser, *args):
448 if isinstance(value, types.StringType):
450 value_conv = booleans[value.strip().lower()]
451 for attribute in args:
452 setattr(parser.values, attribute, value_conv)
454 raise optparse.OptionValueError(
455 "option %s: invalid boolean value: %s (choose from %s)"
456 % (opt, value, boolean_choices))
458 for attribute in args:
459 setattr(parser.values, attribute, value)
461 def CreateOptionParser (theAdditionalOptions=[]):
462 # GUI/Terminal. Default: GUI
463 help_str = "Launch without GUI (in the terminal mode)."
464 o_t = optparse.Option("-t",
466 action="store_false",
470 help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
471 o_b = optparse.Option("-b",
477 help_str = "Launch in GUI mode [default]."
478 o_g = optparse.Option("-g",
484 # Show Desktop (inly in GUI mode). Default: True
485 help_str = "1 to activate GUI desktop [default], "
486 help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
487 help_str += "Ignored in the terminal mode."
488 o_d = optparse.Option("-d",
491 #type="choice", choices=boolean_choices,
493 action="callback", callback=store_boolean, callback_args=('desktop',),
496 help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
497 help_str += "The same as --show-desktop=0."
498 o_o = optparse.Option("-o",
500 action="store_false",
504 # Use logger or log-file. Default: nothing.
505 help_str = "Redirect messages to the CORBA collector."
506 #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
507 o_l = optparse.Option("-l",
509 action="store_const", const="CORBA",
512 help_str = "Redirect messages to the <log-file>"
513 o_f = optparse.Option("-f",
515 metavar="<log-file>",
521 # Execute python scripts. Default: None.
522 help_str = "Python script(s) to be imported. Python scripts are imported "
523 help_str += "in the order of their appearance. In GUI mode python scripts "
524 help_str += "are imported in the embedded python interpreter of current study, "
525 help_str += "otherwise in an external python interpreter. "
526 help_str += "Note: this option is obsolete. Instead you can pass Python script(s) "
527 help_str += "directly as positional parameter."
528 o_u = optparse.Option("-u",
530 metavar="<script1,script2,...>",
536 # Configuration XML file. Default: see defaultUserFile() function
537 help_str = "Parse application settings from the <file> "
538 help_str += "instead of default %s" % defaultUserFile()
539 o_r = optparse.Option("-r",
547 # Use own xterm for each server. Default: False.
548 help_str = "Launch each SALOME server in own xterm console"
549 o_x = optparse.Option("-x",
555 # Modules. Default: Like in configuration files.
556 help_str = "SALOME modules list (where <module1>, <module2> are the names "
557 help_str += "of SALOME modules which should be available in the SALOME session)"
558 o_m = optparse.Option("-m",
560 metavar="<module1,module2,...>",
566 # Embedded servers. Default: Like in configuration files.
567 help_str = "CORBA servers to be launched in the Session embedded mode. "
568 help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
569 help_str += "[by default the value from the configuration files is used]"
570 o_e = optparse.Option("-e",
572 metavar="<server1,server2,...>",
576 callback=check_embedded,
579 # Standalone servers. Default: Like in configuration files.
580 help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
581 help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
582 help_str += "[by default the value from the configuration files is used]"
583 o_s = optparse.Option("-s",
585 metavar="<server1,server2,...>",
589 callback=check_standalone,
592 # Kill with port. Default: False.
593 help_str = "Kill SALOME with the current port"
594 o_p = optparse.Option("-p",
600 # Kill all. Default: False.
601 help_str = "Kill all running SALOME sessions"
602 o_k = optparse.Option("-k",
608 # Additional python interpreters. Default: 0.
609 help_str = "The number of additional external python interpreters to run. "
610 help_str += "Each additional python interpreter is run in separate "
611 help_str += "xterm session with properly set SALOME environment"
612 o_i = optparse.Option("-i",
620 # Splash. Default: True.
621 help_str = "1 to display splash screen [default], "
622 help_str += "0 to disable splash screen. "
623 help_str += "This option is ignored in the terminal mode. "
624 help_str += "It is also ignored if --show-desktop=0 option is used."
625 o_z = optparse.Option("-z",
628 #type="choice", choices=boolean_choices,
630 action="callback", callback=store_boolean, callback_args=('splash',),
634 # Catch exceptions. Default: True.
635 help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
636 help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
637 o_c = optparse.Option("-c",
638 "--catch-exceptions",
640 #type="choice", choices=boolean_choices,
642 action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
643 dest="catch_exceptions",
646 # Print free port and exit
647 help_str = "Print free port and exit"
648 o_a = optparse.Option("--print-port",
650 dest="print_port", default=False,
653 # Do not relink ${HOME}/.omniORB_last.cfg
654 help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
655 o_n = optparse.Option("--nosave-config",
656 action="store_false",
657 dest="save_config", default=True,
660 # Launch with interactive python console. Default: False.
661 help_str = "Launch with interactive python console."
662 o_pi = optparse.Option("--pinter",
667 # Print Naming service port into a user file. Default: False.
668 help_str = "Print Naming Service Port into a user file."
669 o_nspl = optparse.Option("--ns-port-log",
670 metavar="<ns_port_log_file>",
673 dest="ns_port_log_file",
676 # Write/read test script file with help of TestRecorder. Default: False.
677 help_str = "Write/read test script file with help of TestRecorder."
678 o_test = optparse.Option("--test",
679 metavar="<test_script_file>",
682 dest="test_script_file",
685 # Reproducing test script with help of TestRecorder. Default: False.
686 help_str = "Reproducing test script with help of TestRecorder."
687 o_play = optparse.Option("--play",
688 metavar="<play_script_file>",
691 dest="play_script_file",
695 help_str = "Launch session with gdb"
696 o_gdb = optparse.Option("--gdb-session",
698 dest="gdb_session", default=False,
702 help_str = "Launch session with ddd"
703 o_ddd = optparse.Option("--ddd-session",
705 dest="ddd_session", default=False,
710 help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
711 o_valgrind = optparse.Option("--valgrind-session",
713 dest="valgrind_session", default=False,
716 # shutdown-servers. Default: False.
717 help_str = "1 to shutdown standalone servers when leaving python interpreter, "
718 help_str += "0 to keep the standalone servers as daemon [default]. "
719 help_str += "This option is only useful in batchmode "
720 help_str += "(terminal mode or without showing desktop)."
721 o_shutdown = optparse.Option("--shutdown-servers",
723 #type="choice", choices=boolean_choices,
725 action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
726 dest="shutdown_servers",
729 # foreground. Default: True.
730 help_str = "0 and runSalome exits after have launched the gui, "
731 help_str += "1 to launch runSalome in foreground mode [default]."
732 o_foreground = optparse.Option("--foreground",
734 #type="choice", choices=boolean_choices,
736 action="callback", callback=store_boolean, callback_args=('foreground',),
741 help_str = "Wake up a previously closed session. "
742 help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
743 help_str += "If this variable is not setted, the last configuration is taken. "
744 o_wake_up = optparse.Option("--wake-up-session",
746 dest="wake_up_session", default=False,
749 # Launch server processes with a specific command. Default: False.
750 help_str = "Launch server processes with a specific command."
751 o_slc = optparse.Option("--server-launch-cmd",
752 metavar="<server_launch_cmd>",
755 dest="server_launch_cmd",
759 opt_list = [o_t,o_g, # GUI/Terminal
762 o_l,o_f, # Use logger or log-file
763 o_u, # Execute python scripts
764 o_r, # Configuration XML file
767 o_e, # Embedded servers
768 o_s, # Standalone servers
769 o_p, # Kill with port
771 o_i, # Additional python interpreters
773 o_c, # Catch exceptions
774 o_a, # Print free port and exit
775 o_n, # --nosave-config
776 o_pi, # Interactive python console
778 o_test, # Write/read test script file with help of TestRecorder
779 o_play, # Reproducing test script with help of TestRecorder
786 o_slc, # Server launch command
789 #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
790 # "xterm", "modules", "embedded", "standalone",
791 # "portkill", "killall", "interp", "splash",
792 # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
794 opt_list += theAdditionalOptions
796 a_usage = "%prog [options] [STUDY_FILE] [PYTHON_FILE [PYTHON_FILE ...]]"
797 version_str = "Salome %s" % version()
798 pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
802 # -----------------------------------------------------------------------------
805 # Get the environment
808 # this attribute is obsolete
812 def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
814 # Collect launch configuration files:
815 # - The environment variable "<appname>Config" (SalomeAppConfig) which can
816 # define a list of directories (separated by ':' or ';' symbol) is checked
817 # - If the environment variable "<appname>Config" is not set, only
818 # ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
819 # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
820 # so it is not necessary to put it in the "<appname>Config" variable
821 # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
822 # (SalomeApp.xml) which define SALOME configuration
823 # - These directories are analyzed beginning from the last one in the list,
824 # so the first directory listed in "<appname>Config" environment variable
825 # has higher priority: it means that if some configuration options
826 # is found in the next analyzed cofiguration file - it will be replaced
827 # - The last configuration file which is parsed is user configuration file
828 # situated in the home directory (if it exists):
829 # * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
830 # * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
831 # - Command line options have the highest priority and replace options
832 # specified in configuration file(s)
836 config_var = appname+'Config'
839 if os.sys.platform == 'win32':
842 # check KERNEL_ROOT_DIR
844 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
847 For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
848 KERNEL_ROOT_DIR is mandatory.
853 ############################
854 # parse command line options
855 pars = CreateOptionParser(theAdditionalOptions)
856 (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
857 ############################
859 # Process --print-port option
860 if cmd_opts.print_port:
861 from runSalome import searchFreePort
863 print "port:%s"%(os.environ['NSPORT'])
867 # set resources variable SalomeAppConfig if it is not set yet
869 if os.getenv(config_var):
870 if sys.platform == 'win32':
871 dirs += re.split(';', os.getenv(config_var))
873 dirs += re.split('[;|:]', os.getenv(config_var))
876 if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
877 dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
880 gui_available = False
881 if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
882 dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
884 os.environ[config_var] = separator.join(dirs)
886 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
889 dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
893 _opts = {} # associative array of options to be filled
895 # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
897 filename = os.path.join(dir, appname+'.xml')
898 if not os.path.exists(filename):
899 if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
902 p = xml_parser(filename, _opts)
905 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
908 # parse user configuration file
909 # It can be set via --resources=<file> command line option
910 # or is given from default location (see defaultUserFile() function)
911 # If user file for the current version is not found the nearest to it is used
912 user_config = cmd_opts.resources
914 user_config = userFile(appname, cfgname)
915 if verbose(): print "Configure parser: user configuration file is", user_config
916 if not user_config or not os.path.exists(user_config):
917 if verbose(): print "Configure parser: Warning : can not find user configuration file"
920 p = xml_parser(user_config, _opts)
923 if verbose(): print 'Configure parser: Error : can not read user configuration file'
928 args['user_config'] = user_config
929 #print "User Configuration file: ", args['user_config']
931 # set default values for options which are NOT set in config files
932 for aKey in listKeys:
933 if not args.has_key( aKey ):
936 for aKey in boolKeys:
937 if not args.has_key( aKey ):
942 args[file_nam]=[afile]
944 args[appname_nam] = appname
946 # get the port number
947 my_port = getPortNumber()
949 args[port_nam] = my_port
951 ####################################################
952 # apply command-line options to the arguments
953 # each option given in command line overrides the option from xml config file
955 # Options: gui, desktop, log_file, py_scripts, resources,
956 # xterm, modules, embedded, standalone,
957 # portkill, killall, interp, splash,
958 # catch_exceptions, pinter
960 # GUI/Terminal, Desktop, Splash, STUDY_HDF
961 args["session_gui"] = False
962 args[batch_nam] = False
963 args["study_hdf"] = None
964 if cmd_opts.gui is not None:
965 args[gui_nam] = cmd_opts.gui
966 if cmd_opts.batch is not None:
967 args[batch_nam] = True
969 if not gui_available:
970 args[gui_nam] = False
973 args["session_gui"] = True
974 if cmd_opts.desktop is not None:
975 args["session_gui"] = cmd_opts.desktop
976 args[splash_nam] = cmd_opts.desktop
977 if args["session_gui"]:
978 if cmd_opts.splash is not None:
979 args[splash_nam] = cmd_opts.splash
981 args["session_gui"] = False
982 args[splash_nam] = False
985 if cmd_opts.log_file is not None:
986 if cmd_opts.log_file == 'CORBA':
987 args[logger_nam] = True
989 args[file_nam] = [cmd_opts.log_file]
991 # Naming Service port log file
992 if cmd_opts.ns_port_log_file is not None:
993 args["ns_port_log_file"] = cmd_opts.ns_port_log_file
996 args[script_nam] = []
997 if cmd_opts.py_scripts is not None:
998 listlist = cmd_opts.py_scripts
999 for listi in listlist:
1000 if os.sys.platform == 'win32':
1001 args[script_nam] += re.split( "[;,]", listi)
1003 args[script_nam] += re.split( "[:;,]", listi)
1004 for arg in cmd_args:
1005 if arg[-3:] == ".py":
1006 args[script_nam].append(arg)
1007 elif not args["study_hdf"]:
1008 args["study_hdf"] = arg
1013 if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1016 if cmd_opts.modules is not None:
1017 args[modules_nam] = []
1018 listlist = cmd_opts.modules
1019 for listi in listlist:
1020 args[modules_nam] += re.split( "[:;,]", listi)
1022 # if --modules (-m) command line option is not given
1023 # try SALOME_MODULES environment variable
1024 if os.getenv( "SALOME_MODULES" ):
1025 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1029 if cmd_opts.embedded is not None:
1030 args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1033 if cmd_opts.standalone is not None:
1034 args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1036 # Normalize the '--standalone' and '--embedded' parameters
1037 standalone, embedded = process_containers_params( args.get( standalone_nam ),
1038 args.get( embedded_nam ) )
1039 if standalone is not None:
1040 args[ standalone_nam ] = standalone
1041 if embedded is not None:
1042 args[ embedded_nam ] = embedded
1045 if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1046 if cmd_opts.killall is not None: args[killall_nam] = cmd_opts.killall
1049 if cmd_opts.interp is not None:
1050 args[interp_nam] = cmd_opts.interp
1053 if cmd_opts.catch_exceptions is not None:
1054 args[except_nam] = not cmd_opts.catch_exceptions
1056 # Relink config file
1057 if cmd_opts.save_config is not None:
1058 args['save_config'] = cmd_opts.save_config
1060 # Interactive python console
1061 if cmd_opts.pinter is not None:
1062 args[pinter_nam] = cmd_opts.pinter
1064 # Gdb session in xterm
1065 if cmd_opts.gdb_session is not None:
1066 args[gdb_session_nam] = cmd_opts.gdb_session
1068 # Ddd session in xterm
1069 if cmd_opts.ddd_session is not None:
1070 args[ddd_session_nam] = cmd_opts.ddd_session
1073 if cmd_opts.valgrind_session is not None:
1074 args[valgrind_session_nam] = cmd_opts.valgrind_session
1077 if cmd_opts.shutdown_servers is None:
1078 args[shutdown_servers_nam] = 0
1080 args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1084 if cmd_opts.foreground is None:
1085 args[foreground_nam] = 1
1087 args[foreground_nam] = cmd_opts.foreground
1091 if cmd_opts.wake_up_session is not None:
1092 args[wake_up_session_nam] = cmd_opts.wake_up_session
1094 ####################################################
1095 # Add <theAdditionalOptions> values to args
1096 for add_opt in theAdditionalOptions:
1097 cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
1099 ####################################################
1101 # disable signals handling
1102 if args[except_nam] == 1:
1103 os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1106 # now modify SalomeAppConfig environment variable
1107 # to take into account the SALOME modules
1108 if os.sys.platform == 'win32':
1109 dirs = re.split('[;]', os.environ[config_var] )
1111 dirs = re.split('[;|:]', os.environ[config_var] )
1112 for m in args[modules_nam]:
1113 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
1114 d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
1115 d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
1116 #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1117 if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
1119 #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1120 elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
1124 if cmd_opts.test_script_file is not None:
1126 filename = cmd_opts.test_script_file
1127 args[test_nam] += re.split( "[:;,]", filename )
1130 if cmd_opts.play_script_file is not None:
1132 filename = cmd_opts.play_script_file
1133 args[play_nam] += re.split( "[:;,]", filename )
1135 # Server launch command
1136 if cmd_opts.server_launch_cmd is not None:
1137 args["server_launch_cmd"] = cmd_opts.server_launch_cmd
1140 os.environ[config_var] = separator.join(dirs)
1141 #print "Args: ", args