1 import os, glob, string, sys, re
4 # names of tags in XML configuration file
9 # names of attributes in XML configuration file
13 # certain values in XML configuration file ("launch" section)
20 portkill_nam = "portkill"
21 killall_nam = "killall"
22 modules_nam = "modules"
23 pyModules_nam = "pyModules"
24 embedded_nam = "embedded"
25 standalone_nam = "standalone"
26 containers_nam = "containers"
29 except_nam = "noexcepthandler"
31 # values in XML configuration file giving specific module parameters (<module_name> section)
32 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
33 plugins_nam = "plugins"
35 # values passed as arguments, NOT read from XML config file, but set from within this script
36 appname_nam = "appname"
40 # values of boolean type (must be '0' or '1').
41 # xml_parser.boolValue() is used for correct setting
42 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam, except_nam )
45 listKeys = ( containers_nam, embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
47 # return application version (uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION)
49 root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
50 root_dir = os.environ.get( 'GUI_ROOT_DIR', root_dir ) # GUI_ROOT_DIR or KERNEL_ROOT_DIR or "" if both not found
51 filename = root_dir+'/bin/salome/VERSION'
52 str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
53 match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
55 return match.group( 1 )
59 # calculate and return configuration file id in order to unically identify it
60 # for example: for 3.1.0a1 the id is 301000101
61 def version_id( fname ):
62 vers = fname.split(".")
65 mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
68 release = int(mr.group(1))
70 if len(mr.group(2)): dev1 = ord(mr.group(2))
71 if len(mr.group(3)): dev2 = int(mr.group(3))
72 dev = dev1 * 100 + dev2
74 ver = ver * 100 + minor
75 ver = ver * 100 + release
76 ver = ver * 10000 + dev
79 # get user configuration file name
83 return "" # not unknown version
84 filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
85 if os.path.exists(filename):
86 return filename # user preferences file for the current version exists
89 # get all existing user preferences files
90 files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
93 match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
94 if match: f2v[file] = match.group(1)
98 ver = version_id( f2v[file] )
99 if abs(last_version-id0) > abs(ver-id0):
104 # -----------------------------------------------------------------------------
106 ### xml reader for launch configuration file usage
111 def __init__(self, fileName, _opts ):
112 print "Configure parser: processing %s ..." % fileName
115 self.section = section_to_skip
116 parser = xml.sax.make_parser()
117 parser.setContentHandler(self)
118 parser.parse(fileName)
121 def boolValue( self, str ):
122 if str in ("yes", "y", "1"):
124 elif str in ("no", "n", "0"):
130 def startElement(self, name, attrs):
131 self.space.append(name)
134 # if we are analyzing "section" element and its "name" attribute is
135 # either "launch" or module name -- set section_name
136 if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
137 section_name = attrs.getValue( nam_att )
138 if section_name == lanch_nam:
139 self.section = section_name # launch section
140 elif self.opts.has_key( modules_nam ) and \
141 section_name in self.opts[ modules_nam ]:
142 self.section = section_name # <module> section
144 self.section = section_to_skip # any other section
147 # if we are analyzing "parameter" elements - children of either
148 # "section launch" or "section "<module>"" element, then store them
149 # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
150 elif self.section != section_to_skip and \
151 self.space == [doc_tag, sec_tag, par_tag] and \
152 nam_att in attrs.getNames() and \
153 val_att in attrs.getNames():
154 nam = attrs.getValue( nam_att )
155 val = attrs.getValue( val_att )
156 if self.section == lanch_nam: # key for launch section
158 else: # key for <module> section
159 key = self.section + "_" + nam
161 self.opts[key] = self.boolValue( val ) # assign boolean value: 0 or 1
162 elif nam in listKeys:
163 self.opts[key] = val.split( ',' ) # assign list value: []
165 self.opts[key] = val;
169 def endElement(self, name):
172 if self.section != section_to_skip and name == sec_tag:
173 self.section = section_to_skip
176 def characters(self, content):
179 def processingInstruction(self, target, data):
182 def setDocumentLocator(self, locator):
185 def startDocument(self):
189 def endDocument(self):
193 # -----------------------------------------------------------------------------
195 ### searching for launch configuration files
197 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
198 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
199 # - these files are analyzed beginning with the last one (last directory in the list)
200 # - if a key is found in next analyzed cofiguration file - it will be replaced
201 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
202 # - but anyway, if user specifies a certain option in a command line - it will replace the values
203 # - specified in configuration file(s)
204 # - once again the order of settings (next setting replaces the previous ones):
205 # - SalomeApp.xml files in directories specified by SalomeAppConfig env variable
206 # - .SalomeApprc file in user's catalogue
209 config_var = appname+'Config'
210 # set resources variables if not yet set
211 if os.getenv("GUI_ROOT_DIR"):
212 if not os.getenv("SUITRoot"):
213 os.environ["SUITRoot"] = os.getenv("GUI_ROOT_DIR") + "/share/salome"
214 if not os.getenv(config_var):
215 os.environ[config_var] = os.getenv("GUI_ROOT_DIR") + "/share/salome/resources"
218 if not os.getenv("SUITRoot"):
219 os.environ["SUITRoot"] = ""
220 if not os.getenv(config_var):
221 os.environ[config_var] = ""
223 dirs = os.environ[config_var]
224 #abd error om win32 path like W:\dir\di1
225 #print 'Search configuration file in dir ', dirs
226 if os.sys.platform == 'win32':
227 dirs = re.split('[;]', dirs )
229 dirs = re.split('[;|:]', dirs )
230 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
232 _opts = {} # assiciative array of options to be filled
234 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
236 filename = dir+'/'+appname+'.xml'
238 print 'Search configuration file ', filename
241 p = xml_parser(filename, _opts)
244 print "Configure parser: Error : can not read configuration file %s" % filename
247 # SalomeApprc file in user's catalogue
248 filename = userFile()
250 p = xml_parser(filename, _opts)
253 print 'Configure parser: Error : can not read user configuration file'
257 # --- setting default values of keys if they were NOT set in config files ---
258 for aKey in listKeys:
259 if not args.has_key( aKey ):
262 for aKey in boolKeys:
263 if not args.has_key( aKey ):
268 args[file_nam]=[afile]
270 args[appname_nam] = appname
272 ### searching for my port
276 file = open(os.environ["OMNIORB_CONFIG"], "r")
279 l = string.split(s, ":")
280 if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
281 my_port = int(l[len(l)-1])
288 args[port_nam] = my_port
290 # -----------------------------------------------------------------------------
292 ### command line options reader
294 def options_parser(line):
297 for delimiter in [" ", ",", "="]:
299 list += string.split(o, delimiter)
307 while i < len(source):
308 if source[i][0] != '-':
310 elif source[i][1] == '-':
320 while i < len(source) and source[i][0] != '-':
321 result[key].append(source[i])
327 # -----------------------------------------------------------------------------
329 ### read command-line options : each arg given in command line supersedes arg from xml config file
332 cmd_opts = options_parser(sys.argv[1:])
333 kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
338 ### check all options are right
342 if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
343 print "Configure parser: Error : command line error : -%s" % opt
349 if cmd_opts.has_key("h"):
350 print """USAGE: runSalome.py [options]
351 [command line options] :
352 --help or -h : print this help
353 --gui or -g : launching with GUI
354 --terminal -t : launching without gui (to deny --gui)
355 --logger or -l : redirect messages in a CORBA collector
356 --file=filename or -f=filename: redirect messages in a log file
357 --xterm or -x : execute servers in xterm console (messages appear in xterm windows)
358 --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
359 or -m=module1,module2,...
360 --embedded=registry,study,moduleCatalog,cppContainer
361 or -e=registry,study,moduleCatalog,cppContainer
362 : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
363 : (logger,pyContainer,supervContainer can't be embedded
364 --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
365 or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
366 : standalone CORBA servers (default: pyContainer,supervContainer)
367 --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
368 or -c=cpp,python,superv : = get default from -e and -s
369 --portkill or -p : kill the salome with current port
370 --killall or -k : kill all salome sessions
371 --interp=n or -i=n : number of additional xterm to open, with session environment
372 -z : display splash screen
373 -r : disable centralized exception handling mechanism
375 For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
376 The module name (<modulen>) must be uppercase.
377 KERNEL_ROOT_DIR is mandatory.
382 ### apply command-line options to the arguments
393 args[file_nam] = cmd_opts['f']
397 args[interp_nam] = cmd_opts['i']
399 args[modules_nam] = cmd_opts['m']
401 args[embedded_nam] = cmd_opts['e']
403 args[standalone_nam] = cmd_opts['s']
405 args[containers_nam] = cmd_opts['c']
407 args[portkill_nam] = 1
409 args[killall_nam] = 1
413 # if --modules (-m) command line option is not given
414 # try SALOME_MODULES environment variable
415 if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
416 args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
419 # 'terminal' must be processed in the end: to deny any 'gui' options
424 # now modify SalomeAppConfig environment variable
425 if os.sys.platform == 'win32':
426 dirs = re.split('[;]', os.environ[config_var] )
428 dirs = re.split('[;|:]', os.environ[config_var] )
429 for m in args[modules_nam]:
430 if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
431 dirs.append( os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources" )
432 if os.sys.platform == 'win32':
433 os.environ[config_var] = ";".join(dirs)
435 os.environ[config_var] = ":".join(dirs)