Salome HOME
PR: merge from branch BR_auto_V310 tag mergefrom_OCC_development_for_3_2_0a2_10mar06
[modules/yacs.git] / bin / runSalome.py
1 #!/usr/bin/env python
2
3 import sys, os, string, glob, time, pickle
4 import orbmodule
5
6 process_id = {}
7
8 # salome_subdir variable is used for composing paths like $KERNEL_ROOT_DIR/share/salome/resources, etc.
9 # before moving to SUIT-based gui, instead of salome_subdir there was args['appname'] used.
10 # but after - 'appname'  = "SalomeApp", so using it in making the subdirectory is an error.
11 salome_subdir = "salome"
12
13 # -----------------------------------------------------------------------------
14
15 def add_path(directory, variable_name):
16     """Function helper to add environment variables"""
17     if not os.environ.has_key(variable_name):
18         os.environ[variable_name] = ""
19         pass
20     if os.path.exists(directory):
21         newpath=[]
22         for _dir in os.environ[variable_name].split(":"):
23             if os.path.exists(_dir):
24                 if not os.path.samefile(_dir, directory):
25                   newpath.append(_dir)
26             else:
27                 if os.path.abspath(_dir) != os.path.abspath(directory):
28                   newpath.append(_dir)
29             pass
30         import string
31         newpath[:0] = [ directory ]
32         newpath = string.join(newpath,":")
33         os.environ[variable_name] = newpath
34         if variable_name == "PYTHONPATH":
35             sys.path[:0] = [directory]
36
37 # -----------------------------------------------------------------------------
38
39 def get_config():
40     """
41     Get list of modules, paths.
42     
43     Read args from launch configure xml file and command line options.
44     Check variables <module>_ROOT_DIR and set list of used modules.
45     Return args, modules_list, modules_root_dir    
46     """
47     
48     # read args from launch configure xml file and command line options
49     
50     import launchConfigureParser
51     args = launchConfigureParser.args
52     
53     # Check variables <module>_ROOT_DIR
54     # and set list of used modules (without KERNEL)
55
56     modules_list = []
57     if args.has_key("modules"):
58         modules_list += args["modules"]
59     # KERNEL must be last in the list to locate it at the first place in PATH
60     if args["gui"] :
61         modules_list[:0] = ["GUI"]
62     modules_list[:0] = ["KERNEL"]
63     modules_list.reverse()
64
65     modules_root_dir = {}
66
67     to_remove_list=[]
68     for module in modules_list :
69         module_variable=module+"_ROOT_DIR"
70         if not os.environ.has_key(module_variable):
71             print "*******************************************************"
72             print "*"
73             print "* Environment variable",module_variable,"must be set"
74             print "* Module", module, "will be not available"
75             print "*"
76             print "********************************************************"
77             to_remove_list.append(module)
78             continue
79             pass
80         module_root_dir = os.environ[module_variable]
81         modules_root_dir[module]=module_root_dir
82
83     for to_remove in to_remove_list:
84         modules_list.remove(to_remove)
85
86     while "KERNEL" in modules_list:
87         modules_list.remove("KERNEL")
88         pass
89
90     while "GUI" in modules_list:
91         modules_list.remove("GUI")
92         pass
93
94     if "SUPERV" in modules_list and not 'superv' in args['standalone']:
95         args['standalone'].append("superv")
96         pass
97    
98     return args, modules_list, modules_root_dir
99
100 # -----------------------------------------------------------------------------
101
102 def set_env(args, modules_list, modules_root_dir):
103     """Add to the PATH-variables modules specific paths"""
104     
105     python_version="python%d.%d" % sys.version_info[0:2]
106     modules_root_dir_list = []
107     if args["gui"] :
108         modules_list = modules_list[:] + ["GUI"] 
109     modules_list = modules_list[:] + ["KERNEL"] 
110     for module in modules_list :
111         if modules_root_dir.has_key(module):
112             module_root_dir = modules_root_dir[module]
113             modules_root_dir_list[:0] = [module_root_dir]
114             add_path(os.path.join(module_root_dir,"lib",salome_subdir),
115                      "LD_LIBRARY_PATH")
116             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
117                      "PATH")
118             if os.path.exists(module_root_dir + "/examples") :
119                 add_path(os.path.join(module_root_dir,"examples"),
120                          "PYTHONPATH")
121                 pass
122             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
123                      "PYTHONPATH")
124             add_path(os.path.join(module_root_dir,"lib",
125                                   python_version,"site-packages",
126                                   salome_subdir),
127                      "PYTHONPATH")
128             add_path(os.path.join(module_root_dir,"lib",salome_subdir),
129                      "PYTHONPATH")
130             add_path(os.path.join(module_root_dir,"lib",
131                                   python_version,"site-packages",
132                                   salome_subdir,
133                                   "shared_modules"),
134                      "PYTHONPATH")
135             pass
136         pass
137
138
139     os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
140     
141     # set trace environment variable
142     
143     if not os.environ.has_key("SALOME_trace"):
144         os.environ["SALOME_trace"]="local"
145     if args['file']:
146         os.environ["SALOME_trace"]="file:"+args['file'][0]
147     if args['logger']:
148         os.environ["SALOME_trace"]="with_logger"
149
150     # set environment for SMESH plugins
151
152     if "SMESH" in modules_list:
153         os.environ["SMESH_MeshersList"]="StdMeshers"
154         if not os.environ.has_key("SALOME_StdMeshersResources"):
155             os.environ["SALOME_StdMeshersResources"] \
156             = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources"
157             pass
158         if args.has_key("SMESH_plugins"):
159             for plugin in args["SMESH_plugins"]:
160                 plugin_root = ""
161                 if os.environ.has_key(plugin+"_ROOT_DIR"):
162                     plugin_root = os.environ[plugin+"_ROOT_DIR"]
163                 else:
164                     # workaround to avoid modifications of existing environment
165                     if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
166                         plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
167                         pass
168                     pass
169                 if plugin_root != "":
170                     os.environ["SMESH_MeshersList"] \
171                     = os.environ["SMESH_MeshersList"]+":"+plugin
172                     if not os.environ.has_key("SALOME_"+plugin+"Resources"):
173                         os.environ["SALOME_"+plugin+"Resources"] \
174                         = plugin_root+"/share/"+args["appname"]+"/resources"
175                     add_path(os.path.join(plugin_root,"lib",python_version,
176                                           "site-packages",salome_subdir),
177                              "PYTHONPATH")
178                     add_path(os.path.join(plugin_root,"lib",salome_subdir),
179                              "PYTHONPATH")
180                     add_path(os.path.join(plugin_root,"lib",salome_subdir),
181                              "LD_LIBRARY_PATH")
182                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
183                              "PYTHONPATH")
184                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
185                              "PATH")
186             pass
187         pass
188
189     # set environment for SUPERV module
190     os.environ["ENABLE_MACRO_NODE"]="1"
191     # set resources variables if not yet set
192     # Done now by launchConfigureParser.py
193     #if os.getenv("GUI_ROOT_DIR"):
194         #if not os.getenv("SUITRoot"): os.environ["SUITRoot"] =  os.getenv("GUI_ROOT_DIR") + "/share/salome"
195         #if not os.getenv("SalomeAppConfig"): os.environ["SalomeAppConfig"] =  os.getenv("GUI_ROOT_DIR") + "/share/salome/resources"
196
197     # set CSF_PluginDefaults variable only if it is not customized
198     # by the user
199     if not os.getenv("CSF_PluginDefaults"):
200         os.environ["CSF_PluginDefaults"] \
201         = os.path.join(modules_root_dir["KERNEL"],"share",
202                        salome_subdir,"resources")
203     os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
204     = os.path.join(modules_root_dir["KERNEL"],"share",
205                    salome_subdir,"resources")
206
207     if "GEOM" in modules_list:
208         print "GEOM OCAF Resources"
209         os.environ["CSF_GEOMDS_ResourcesDefaults"] \
210         = os.path.join(modules_root_dir["GEOM"],"share",
211                        salome_subdir,"resources")
212         print "GEOM Shape Healing Resources"
213         os.environ["CSF_ShHealingDefaults"] \
214         = os.path.join(modules_root_dir["GEOM"],"share",
215                        salome_subdir,"resources")
216
217 # -----------------------------------------------------------------------------
218
219 from killSalome import killAllPorts
220
221 def killLocalPort():
222     """
223     kill servers from a previous SALOME exection, if needed,
224     on the CORBA port given in args of runSalome
225     """
226     
227     from killSalomeWithPort import killMyPort
228     my_port=str(args['port'])
229     try:
230         killMyPort(my_port)
231     except:
232         print "problem in killLocalPort()"
233         pass
234     pass
235     
236 def givenPortKill(port):
237     """
238     kill servers from a previous SALOME exection, if needed,
239     on the same CORBA port
240     """
241     
242     from killSalomeWithPort import killMyPort
243     my_port=port
244     try:
245         killMyPort(my_port)
246     except:
247         print "problem in LocalPortKill(), killMyPort("<<port<<")"
248         pass
249     pass
250
251 def kill_salome(args):
252     """
253     Kill servers from previous SALOME executions, if needed;
254     depending on args 'killall' or 'portkill', kill all executions,
255     or only execution on the same CORBA port
256     """
257
258     if args['killall']:
259         killAllPorts()
260     elif args['portkill']:
261         givenPortKill(str(args['port']))
262         
263 # -----------------------------------------------------------------------------
264 #
265 # Definition des classes d'objets pour le lancement des Server CORBA
266 #
267
268 class Server:
269     """Generic class for CORBA server launch"""
270
271     def initArgs(self):
272         self.PID=None
273         self.CMD=[]
274         self.ARGS=[]    
275         if self.args['xterm']:
276             self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
277
278     def __init__(self,args):
279         self.args=args
280         self.initArgs()
281
282
283     def run(self):
284         global process_id
285         myargs=self.ARGS
286         if self.args['xterm']:
287             # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
288             env_ld_library_path=['env', 'LD_LIBRARY_PATH='
289                                  + os.getenv("LD_LIBRARY_PATH")]
290             myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
291         command = myargs + self.CMD
292         print "command = ", command
293         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
294         process_id[pid]=self.CMD
295         self.PID = pid
296
297
298 class InterpServer(Server):
299     def __init__(self,args):
300         self.args=args
301         env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
302         self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
303         #self.CMD=['xterm', '-e', 'python']
304        
305     def run(self):
306         global process_id
307         command = self.CMD
308         #print "command = ", command
309         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
310         process_id[pid]=self.CMD
311         self.PID = pid
312
313 # ---
314
315 class CatalogServer(Server):
316     def __init__(self,args):
317         self.args=args
318         self.initArgs()
319         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
320         self.SCMD2=[]
321         home_dir=os.getenv('HOME')
322         if home_dir is not None:
323             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
324
325     def setpath(self,modules_list,modules_root_dir):
326         cata_path=[]
327         list_modules = modules_list[:]
328         list_modules.reverse()
329         if self.args["gui"] :
330             list_modules = ["KERNEL", "GUI"] + list_modules
331         else :
332             list_modules = ["KERNEL"] + list_modules
333         for module in list_modules:
334             if modules_root_dir.has_key(module):
335                 module_root_dir=modules_root_dir[module]
336                 module_cata=module+"Catalog.xml"
337                 #print "   ", module_cata
338                 cata_path.extend(
339                     glob.glob(os.path.join(module_root_dir,
340                                            "share",salome_subdir,
341                                            "resources",module_cata)))
342                 pass
343             pass
344         self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
345
346 # ---
347
348 class SalomeDSServer(Server):
349     def __init__(self,args):
350         self.args=args
351         self.initArgs()
352         self.CMD=['SALOMEDS_Server']
353
354 # ---
355
356 class RegistryServer(Server):
357     def __init__(self,args):
358         self.args=args
359         self.initArgs()
360         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
361
362 # ---
363
364 class ContainerCPPServer(Server):
365     def __init__(self,args):
366         self.args=args
367         self.initArgs()
368         self.CMD=['SALOME_Container','FactoryServer']
369
370 # ---
371
372 class ContainerPYServer(Server):
373     def __init__(self,args):
374         self.args=args
375         self.initArgs()
376         self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
377
378 # ---
379
380 class ContainerSUPERVServer(Server):
381     def __init__(self,args):
382         self.args=args
383         self.initArgs()
384         self.CMD=['SALOME_Container','SuperVisionContainer']
385
386 # ---
387
388 class LoggerServer(Server):
389     def __init__(self,args):
390         self.args=args
391         self.initArgs()
392         self.CMD=['SALOME_Logger_Server', 'logger.log']
393
394 # ---
395
396 class SessionServer(Server):
397     def __init__(self,args):
398         self.args = args.copy()
399         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
400         self.args['xterm']=0
401         #
402         self.initArgs()
403         self.SCMD1=['SALOME_Session_Server']
404         self.SCMD2=[]
405         if 'registry' in self.args['embedded']:
406             self.SCMD1+=['--with','Registry',
407                          '(','--salome_session','theSession',')']
408         if 'moduleCatalog' in self.args['embedded']:
409             self.SCMD1+=['--with','ModuleCatalog','(','-common']
410             home_dir=os.getenv('HOME')
411             if home_dir is not None:
412                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
413             self.SCMD2+=[')']
414         if 'study' in self.args['embedded']:
415             self.SCMD2+=['--with','SALOMEDS','(',')']
416         if 'cppContainer' in self.args['embedded']:
417             self.SCMD2+=['--with','Container','(','FactoryServer',')']
418         if 'SalomeAppEngine' in self.args['embedded']:
419             self.SCMD2+=['--with','SalomeAppEngine','(',')']
420             
421         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
422             self.SCMD2+=['CPP']
423         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
424             self.SCMD2+=['PY']
425         if 'supervContainer' in self.args['containers'] or 'supervContainer' in self.args['standalone']:
426             self.SCMD2+=['SUPERV']
427         if self.args['gui']:
428             self.SCMD2+=['GUI']
429         if self.args['splash'] and self.args['gui']:
430             self.SCMD2+=['SPLASH']
431         if self.args['noexcepthandler']:
432             self.SCMD2+=['noexcepthandler']
433         if self.args.has_key('modules'):
434             self.SCMD2+=['--modules (']
435             for mod in self.args['modules']:
436                 self.SCMD2+=[mod + ':']
437             self.SCMD2+=[')']    
438
439     def setpath(self,modules_list,modules_root_dir):
440         cata_path=[]
441         list_modules = modules_list[:]
442         list_modules.reverse()
443         if self.args["gui"] :
444             list_modules = ["KERNEL", "GUI"] + list_modules
445         else :
446             list_modules = ["KERNEL"] + list_modules
447         for module in list_modules:
448             module_root_dir=modules_root_dir[module]
449             module_cata=module+"Catalog.xml"
450             #print "   ", module_cata
451             cata_path.extend(
452                 glob.glob(os.path.join(module_root_dir,"share",
453                                        salome_subdir,"resources",
454                                        module_cata)))
455         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
456             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
457         else:
458             self.CMD=self.SCMD1 + self.SCMD2
459       
460 # ---
461
462 class ContainerManagerServer(Server):
463     def __init__(self,args):
464         self.args=args
465         self.initArgs()
466         self.SCMD1=['SALOME_ContainerManagerServer']
467         self.SCMD2=[]
468         if args["gui"] :
469             if 'registry' in self.args['embedded']:
470                 self.SCMD1+=['--with','Registry',
471                              '(','--salome_session','theSession',')']
472             if 'moduleCatalog' in self.args['embedded']:
473                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
474                 self.SCMD2+=['-personal',
475                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
476             if 'study' in self.args['embedded']:
477                 self.SCMD2+=['--with','SALOMEDS','(',')']
478             if 'cppContainer' in self.args['embedded']:
479                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
480         
481     def setpath(self,modules_list,modules_root_dir):
482         cata_path=[]
483         list_modules = modules_list[:]
484         list_modules.reverse()
485         if self.args["gui"] :
486             list_modules = ["GUI"] + list_modules
487         for module in ["KERNEL"] + list_modules:
488             if modules_root_dir.has_key(module):
489                 module_root_dir=modules_root_dir[module]
490                 module_cata=module+"Catalog.xml"
491                 #print "   ", module_cata
492                 cata_path.extend(
493                     glob.glob(os.path.join(module_root_dir,"share",
494                                            self.args['appname'],"resources",
495                                            module_cata)))
496                 pass
497             pass
498         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
499             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
500         else:
501             self.CMD=self.SCMD1 + self.SCMD2
502
503 class NotifyServer(Server):
504     def __init__(self,args,modules_root_dir):
505         self.args=args
506         self.initArgs()
507         self.modules_root_dir=modules_root_dir
508         myLogName = os.environ["LOGNAME"]
509         self.CMD=['notifd','-c',
510                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/channel.cfg',
511                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
512                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
513                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
514                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
515                   ]
516
517 #
518 # -----------------------------------------------------------------------------
519
520 def startGUI():
521     """Salome Session Graphic User Interface activation"""
522     import Engines
523     import SALOME
524     import SALOMEDS
525     import SALOME_ModuleCatalog
526     reload(Engines)
527     reload(SALOME)
528     reload(SALOMEDS)
529     import SALOME_Session_idl
530     session=clt.waitNS("/Kernel/Session",SALOME.Session)
531     session.GetInterface()
532   
533 # -----------------------------------------------------------------------------
534
535 def startSalome(args, modules_list, modules_root_dir):
536     """Launch all SALOME servers requested by args"""
537     init_time = os.times()
538
539     print "startSalome ", args
540     
541     #
542     # Initialisation ORB et Naming Service
543     #
544    
545     clt=orbmodule.client()
546
547     # (non obligatoire) Lancement Logger Server
548     # et attente de sa disponibilite dans le naming service
549     #
550
551     if args['logger']:
552         myServer=LoggerServer(args)
553         myServer.run()
554         clt.waitLogger("Logger")
555
556     # Notify Server launch
557     #
558
559     print "Notify Server to launch"
560
561     myServer=NotifyServer(args,modules_root_dir)
562     myServer.run()
563
564     #
565     # Lancement Registry Server,
566     # attente de la disponibilite du Registry dans le Naming Service
567     #
568
569     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
570         myServer=RegistryServer(args)
571         myServer.run()
572         clt.waitNSPID("/Registry",myServer.PID)
573
574     #
575     # Lancement Catalog Server,
576     # attente de la disponibilite du Catalog Server dans le Naming Service
577     #
578     
579
580     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
581         cataServer=CatalogServer(args)
582         cataServer.setpath(modules_list,modules_root_dir)
583         cataServer.run()
584         import SALOME_ModuleCatalog
585         clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
586
587     #
588     # Lancement SalomeDS Server,
589     # attente de la disponibilite du SalomeDS dans le Naming Service
590     #
591
592     #print "ARGS = ",args
593     if ('study' not in args['embedded']) | (args["gui"] == 0):
594         print "RunStudy"
595         myServer=SalomeDSServer(args)
596         myServer.run()
597         clt.waitNSPID("/myStudyManager",myServer.PID)
598
599     #
600     # Lancement ContainerManagerServer
601     #
602     
603     myCmServer = ContainerManagerServer(args)
604     myCmServer.setpath(modules_list,modules_root_dir)
605     myCmServer.run()
606
607
608     from Utils_Identity import getShortHostName
609     
610     if os.getenv("HOSTNAME") == None:
611         if os.getenv("HOST") == None:
612             os.environ["HOSTNAME"]=getShortHostName()
613         else:
614             os.environ["HOSTNAME"]=os.getenv("HOST")
615
616     theComputer = getShortHostName()
617     
618     #
619     # Lancement Container C++ local,
620     # attente de la disponibilite du Container C++ local dans le Naming Service
621     #
622
623     if 'cppContainer' in args['standalone']:
624         myServer=ContainerCPPServer(args)
625         myServer.run()
626         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
627
628     #
629     # Lancement Container Python local,
630     # attente de la disponibilite du Container Python local
631     # dans le Naming Service
632     #
633
634     if 'pyContainer' in args['standalone']:
635         myServer=ContainerPYServer(args)
636         myServer.run()
637         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
638
639     #
640     # Lancement Container Supervision local,
641     # attente de la disponibilite du Container Supervision local
642     # dans le Naming Service
643     #
644
645     if 'supervContainer' in args['standalone']:
646         myServer=ContainerSUPERVServer(args)
647         myServer.run()
648         clt.waitNSPID("/Containers/" + theComputer + "/SuperVisionContainer",myServer.PID)
649
650     #
651     # Lancement Session Server
652     #
653
654     if args["gui"]:
655         mySessionServ = SessionServer(args)
656         mySessionServ.setpath(modules_list,modules_root_dir)
657         mySessionServ.run()
658 ##----------------        
659
660         # Attente de la disponibilite du Session Server dans le Naming Service
661         #
662
663         import Engines
664         import SALOME
665         import SALOMEDS
666         import SALOME_ModuleCatalog
667         reload(Engines)
668         reload(SALOME)
669         reload(SALOMEDS)
670         import SALOME_Session_idl
671         session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
672
673     end_time = os.times()
674     print
675     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
676                                                          - init_time[4])
677
678     # ASV start GUI without Loader
679     #if args['gui']:
680     #    session.GetInterface()
681
682     #
683     # additionnal external python interpreters
684     #
685     nbaddi=0
686     
687     try:
688         if 'interp' in args:
689             if args['interp']:
690                 nbaddi = int(args['interp'][0])
691     except:
692         import traceback
693         traceback.print_exc()
694         print "-------------------------------------------------------------"
695         print "-- to get an external python interpreter:runSalome --interp=1"
696         print "-------------------------------------------------------------"
697         
698     print "additional external python interpreters: ", nbaddi
699     if nbaddi:
700         for i in range(nbaddi):
701             print "i=",i
702             anInterp=InterpServer(args)
703             anInterp.run()
704     
705     return clt
706
707 # -----------------------------------------------------------------------------
708
709 def useSalome(args, modules_list, modules_root_dir):
710     """
711     Launch all SALOME servers requested by args,
712     save list of process, give info to user,
713     show registered objects in Naming Service.
714     """
715     
716     clt=None
717     try:
718         clt = startSalome(args, modules_list, modules_root_dir)
719     except:
720         import traceback
721         traceback.print_exc()
722         print
723         print
724         print "--- erreur au lancement Salome ---"
725         
726     #print process_id
727
728     from killSalomeWithPort import getPiDict
729     filedict = getPiDict(args['port'])
730
731     process_ids = []
732     try:
733         fpid=open(filedict, 'r')
734         process_ids=pickle.load(fpid)
735         fpid.close()
736     except:
737         pass
738     
739     fpid=open(filedict, 'w')
740     process_ids.append(process_id)
741     pickle.dump(process_ids,fpid)
742     fpid.close()
743     
744     print """
745     Saving of the dictionary of Salome processes in %s
746     To kill SALOME processes from a console (kill all sessions from all ports):
747       python killSalome.py 
748     To kill SALOME from the present interpreter, if it is not closed :
749       killLocalPort()      --> kill this session
750                                (use CORBA port from args of runSalome)
751       givenPortKill(port)  --> kill a specific session with given CORBA port 
752       killAllPorts()       --> kill all sessions
753     
754     runSalome, with --killall option, starts with killing
755     the processes resulting from the previous execution.
756     """%filedict
757     
758     #
759     #  Impression arborescence Naming Service
760     #
761     
762     if clt != None:
763         print
764         print " --- registered objects tree in Naming Service ---"
765         clt.showNS()
766
767     return clt
768
769 # -----------------------------------------------------------------------------
770
771 def registerEnv(args, modules_list, modules_root_dir):
772     """
773     Register args, modules_list, modules_root_dir in a file
774     for further use, when SALOME is launched embedded in an other application.
775     """
776     fileEnv = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
777             + '_' + args['appname'].upper() + '_env'
778     fenv=open(fileEnv,'w')
779     pickle.dump((args, modules_list, modules_root_dir),fenv)
780     fenv.close()
781     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
782
783 # -----------------------------------------------------------------------------
784
785 def no_main():
786     """Salome Launch, when embedded in other application"""
787     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
788     fenv=open(fileEnv,'r')
789     args, modules_list, modules_root_dir = pickle.load(fenv)
790     fenv.close()
791     kill_salome(args)
792     clt = useSalome(args, modules_list, modules_root_dir)
793     return clt
794
795 # -----------------------------------------------------------------------------
796
797 def main():
798     """Salome launch as a main application"""
799     args, modules_list, modules_root_dir = get_config()
800     kill_salome(args)
801     set_env(args, modules_list, modules_root_dir)
802     clt = useSalome(args, modules_list, modules_root_dir)
803     return clt,args
804
805 # -----------------------------------------------------------------------------
806
807 if __name__ == "__main__":
808    import user
809    clt,args = main()