Salome HOME
bug fix
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## @package runSalome
26 # \brief Module that provides services to launch SALOME
27 #
28
29 import sys, os, string, glob, time, pickle, re
30 import orbmodule
31 import setenv
32 from launchConfigureParser import verbose
33 from server import process_id, Server
34 import json
35 from salomeLauncherUtils import formatScriptsAndArgs
36 import subprocess
37 import PortManager
38
39 # -----------------------------------------------------------------------------
40
41 from killSalome import killAllPorts
42
43 def killLocalPort():
44     """
45     kill servers from a previous SALOME exection, if needed,
46     on the CORBA port given in args of runSalome
47     """
48
49     from killSalomeWithPort import killMyPort
50     my_port=str(args['port'])
51     try:
52         killMyPort(my_port)
53     except:
54         print "problem in killLocalPort()"
55         pass
56     pass
57
58 def givenPortKill(port):
59     """
60     kill servers from a previous SALOME exection, if needed,
61     on the same CORBA port
62     """
63
64     from killSalomeWithPort import killMyPort
65     my_port=port
66     try:
67         killMyPort(my_port)
68     except:
69         print "problem in LocalPortKill(), killMyPort("<<port<<")"
70         pass
71     pass
72
73 def kill_salome(args):
74     """
75     Kill servers from previous SALOME executions, if needed;
76     depending on args 'killall' or 'portkill', kill all executions,
77     or only execution on the same CORBA port
78     """
79
80     if args['killall']:
81         killAllPorts()
82     elif args['portkill']:
83         givenPortKill(str(args['port']))
84
85 # -----------------------------------------------------------------------------
86 #
87 # Class definitions to launch CORBA Servers
88 #
89
90 class InterpServer(Server):
91     def __init__(self,args):
92         self.args=args
93         if sys.platform != "win32":
94           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
95           self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
96         else:
97           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
98
99     def run(self):
100         global process_id
101         command = self.CMD
102         print "INTERPSERVER::command = ", command
103         if sys.platform == "win32":
104           import win32pm
105           pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
106         else:
107           pid = os.spawnvp(os.P_NOWAIT, command[0], command)
108         process_id[pid]=self.CMD
109         self.PID = pid
110
111 # ---
112
113 def get_cata_path(list_modules,modules_root_dir):
114     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
115     """
116     modules_cata={}
117     cata_path=[]
118
119     for module in list_modules:
120         if modules_root_dir.has_key(module):
121             module_root_dir=modules_root_dir[module]
122             module_cata=module+"Catalog.xml"
123             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
124
125             if os.path.exists(cata_file):
126                 cata_path.append(cata_file)
127                 modules_cata[module]=cata_file
128             else:
129                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
130                 if os.path.exists(cata_file):
131                     cata_path.append(cata_file)
132                     modules_cata[module]=cata_file
133
134     for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
135         if os.path.exists(path):
136             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
137                 module_name= os.path.basename(cata_file)[:-11]
138                 if not modules_cata.has_key(module_name):
139                     cata_path.append(cata_file)
140                     modules_cata[module_name]=cata_file
141
142     return cata_path
143
144
145
146 class CatalogServer(Server):
147     def __init__(self,args):
148         self.args=args
149         self.initArgs()
150         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
151         self.SCMD2=[]
152         home_dir=os.getenv('HOME')
153         if home_dir is not None:
154             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
155
156     def setpath(self,modules_list,modules_root_dir):
157         list_modules = modules_list[:]
158         list_modules.reverse()
159         if self.args["gui"] :
160             list_modules = ["KERNEL", "GUI"] + list_modules
161         else :
162             list_modules = ["KERNEL"] + list_modules
163
164         cata_path=get_cata_path(list_modules,modules_root_dir)
165
166         self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
167
168 # ---
169
170 class SalomeDSServer(Server):
171     def __init__(self,args):
172         self.args=args
173         self.initArgs()
174         self.CMD=['SALOMEDS_Server']
175
176 # ---
177
178 class ConnectionManagerServer(Server):
179     def __init__(self,args):
180         self.args=args
181         self.initArgs()
182         self.CMD=['SALOME_ConnectionManagerServer']
183
184 # ---
185
186 class RegistryServer(Server):
187     def __init__(self,args):
188         self.args=args
189         self.initArgs()
190         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
191
192 # ---
193
194 class ContainerCPPServer(Server):
195     def __init__(self,args):
196         self.args=args
197         self.initArgs()
198         self.CMD=['SALOME_Container','FactoryServer']
199
200 # ---
201
202 class LoggerServer(Server):
203     def __init__(self,args):
204         self.args=args
205         self.initArgs()
206         from salome_utils import generateFileName
207         if sys.platform == "win32": dirpath = os.environ["HOME"]
208         else:                       dirpath = "/tmp"
209         logfile = generateFileName( dirpath,
210                                     prefix="logger",
211                                     extension="log",
212                                     with_username=True,
213                                     with_hostname=True,
214                                     with_port=True)
215         print "==========================================================="
216         print "Logger server: put log to the file:"
217         print logfile
218         print "==========================================================="
219         self.CMD=['SALOME_Logger_Server', logfile]
220         pass
221     pass # end of LoggerServer class
222
223 # ---
224
225 class SessionServer(Server):
226     def __init__(self,args,modules_list,modules_root_dir):
227         self.args = args.copy()
228         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
229         #self.args['xterm']=0
230         #
231         self.initArgs()
232         self.SCMD1=['SALOME_Session_Server']
233         self.SCMD2=[]
234         if 'registry' in self.args['embedded']:
235             self.SCMD1+=['--with','Registry',
236                          '(','--salome_session','theSession',')']
237         if 'moduleCatalog' in self.args['embedded']:
238             self.SCMD1+=['--with','ModuleCatalog','(','-common']
239             home_dir=os.getenv('HOME')
240             if home_dir is not None:
241                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
242             self.SCMD2+=[')']
243         if 'study' in self.args['embedded']:
244             self.SCMD2+=['--with','SALOMEDS','(',')']
245         if 'cppContainer' in self.args['embedded']:
246             self.SCMD2+=['--with','Container','(','FactoryServer',')']
247         if 'SalomeAppEngine' in self.args['embedded']:
248             self.SCMD2+=['--with','SalomeAppEngine','(',')']
249
250         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
251             self.SCMD2+=['CPP']
252         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
253             raise Exception('Python containers no longer supported')
254         if self.args['gui']:
255             session_gui = True
256             if self.args.has_key('session_gui'):
257                 session_gui = self.args['session_gui']
258             if session_gui:
259                 self.SCMD2+=['GUI']
260                 if self.args['splash']:
261                     self.SCMD2+=['SPLASH']
262                     pass
263                 if self.args['study_hdf'] is not None:
264                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
265                     pass
266                 pass
267                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
268                     msg = json.dumps(self.args['pyscript'])
269                     self.SCMD2+=['--pyscript=%s'%(msg)]
270                     pass
271                 pass
272             pass
273         if self.args['noexcepthandler']:
274             self.SCMD2+=['noexcepthandler']
275         if self.args.has_key('user_config'):
276             self.SCMD2+=['--resources=%s'%self.args['user_config']]
277         if self.args.has_key('modules'):
278             list_modules = []
279             #keep only modules with GUI
280             for m in modules_list:
281               if m not in modules_root_dir:
282                 list_modules.insert(0,m)
283               else:
284                 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
285                 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
286                 if os.path.exists(fr1) or os.path.exists(fr2):
287                   list_modules.insert(0,m)
288             list_modules.reverse()
289             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
290             pass
291         pass
292
293     def setpath(self,modules_list,modules_root_dir):
294         list_modules = modules_list[:]
295         list_modules.reverse()
296         if self.args["gui"] :
297             list_modules = ["KERNEL", "GUI"] + list_modules
298         else :
299             list_modules = ["KERNEL"] + list_modules
300
301         cata_path=get_cata_path(list_modules,modules_root_dir)
302
303         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
304             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
305             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
306         else:
307             self.CMD=self.SCMD1 + self.SCMD2
308         if self.args.has_key('test'):
309             self.CMD+=['-test'] + self.args['test']
310         elif self.args.has_key('play'):
311             self.CMD+=['-play'] + self.args['play']
312
313         if self.args["gdb_session"] or self.args["ddd_session"]:
314             f = open(".gdbinit4salome", "w")
315             f.write("set args ")
316             args = " ".join(self.CMD[1:])
317             args = args.replace("(", "\(")
318             args = args.replace(")", "\)")
319             f.write(args)
320             f.write("\n")
321             f.close()
322             if self.args["ddd_session"]:
323                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
324             elif self.args["gdb_session"]:
325                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
326                 pass
327             pass
328
329         if self.args["valgrind_session"]:
330             l = ["valgrind"]
331             val = os.getenv("VALGRIND_OPTIONS")
332             if val:
333                 l += val.split()
334                 pass
335             self.CMD = l + self.CMD
336             pass
337
338 # ---
339
340 class LauncherServer(Server):
341     def __init__(self,args):
342         self.args=args
343         self.initArgs()
344         self.SCMD1=['SALOME_LauncherServer']
345         self.SCMD2=[]
346         if args["gui"] :
347             if 'registry' in self.args['embedded']:
348                 self.SCMD1+=['--with','Registry',
349                              '(','--salome_session','theSession',')']
350             if 'moduleCatalog' in self.args['embedded']:
351                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
352                 self.SCMD2+=['-personal',
353                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
354             if 'study' in self.args['embedded']:
355                 self.SCMD2+=['--with','SALOMEDS','(',')']
356             if 'cppContainer' in self.args['embedded']:
357                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
358
359     def setpath(self,modules_list,modules_root_dir):
360         list_modules = modules_list[:]
361         list_modules.reverse()
362         if self.args["gui"] :
363             list_modules = ["KERNEL", "GUI"] + list_modules
364         else :
365             list_modules = ["KERNEL"] + list_modules
366
367         cata_path=get_cata_path(list_modules,modules_root_dir)
368
369         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
370             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
371             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
372         else:
373             self.CMD=self.SCMD1 + self.SCMD2
374
375 class NotifyServer(Server):
376     def __init__(self,args,modules_root_dir):
377         self.args=args
378         self.initArgs()
379         self.modules_root_dir=modules_root_dir
380         myLogName = os.environ["LOGNAME"]
381         self.CMD=['notifd','-c',
382                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
383                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
384                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
385                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
386                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
387                   ]
388
389 #
390 # -----------------------------------------------------------------------------
391
392 def startGUI(clt):
393     """Salome Session Graphic User Interface activation"""
394     import Engines
395     import SALOME
396     import SALOMEDS
397     import SALOME_ModuleCatalog
398     import SALOME_Session_idl
399     session=clt.waitNS("/Kernel/Session",SALOME.Session)
400     session.GetInterface()
401
402 # -----------------------------------------------------------------------------
403
404 def startSalome(args, modules_list, modules_root_dir):
405     """Launch all SALOME servers requested by args"""
406     init_time = os.times()
407
408     if verbose(): print "startSalome ", args
409
410     #
411     # Set server launch command
412     #
413     if args.has_key('server_launch_mode'):
414         Server.set_server_launch_mode(args['server_launch_mode'])
415
416     #
417     # Wake up session option
418     #
419     if args['wake_up_session']:
420         if "OMNIORB_CONFIG" not in os.environ:
421             from salome_utils import generateFileName
422             omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
423             kwargs={}
424             if omniorbUserPath is not None:
425                 kwargs["with_username"]=True
426
427             last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
428                                                    suffix="last",
429                                                    extension="cfg",
430                                                    hidden=True,
431                                                    **kwargs)
432             os.environ['OMNIORB_CONFIG'] = last_running_config
433             pass
434         pass
435
436     #
437     # Initialisation ORB and Naming Service
438     #
439
440     clt=orbmodule.client(args)
441
442     #
443     # Wake up session option
444     #
445     if args['wake_up_session']:
446         import Engines
447         import SALOME
448         import SALOMEDS
449         import SALOME_ModuleCatalog
450         import SALOME_Session_idl
451         session = clt.waitNS("/Kernel/Session",SALOME.Session)
452         status = session.GetStatSession()
453         if status.activeGUI:
454             from salome_utils import getPortNumber
455             port = getPortNumber()
456             msg  = "Warning :"
457             msg += "\n"
458             msg += "Session GUI for port number %s is already active."%(port)
459             msg += "\n"
460             msg += "If you which to wake up another session,"
461             msg += "\n"
462             msg += "please use variable OMNIORB_CONFIG"
463             msg += "\n"
464             msg += "to get the correct session object in naming service."
465             sys.stdout.write(msg+"\n")
466             sys.stdout.flush()
467             return clt
468         session.GetInterface()
469         args["session_object"] = session
470         return clt
471
472     # Save Naming service port name into
473     # the file args["ns_port_log_file"]
474     if args.has_key('ns_port_log_file'):
475       omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
476       file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
477       f = open(file_name, "w")
478       f.write(os.environ['NSPORT'])
479       f.close()
480
481     # Launch Logger Server (optional)
482     # and wait until it is registered in naming service
483     #
484
485     if args['logger']:
486         myServer=LoggerServer(args)
487         myServer.run()
488         clt.waitLogger("Logger")
489
490     # Notify Server launch
491     #
492
493     if sys.platform != "win32":
494       if verbose(): print "Notify Server to launch"
495
496       myServer=NotifyServer(args,modules_root_dir)
497       myServer.run()
498
499     # Launch  Session Server (to show splash ASAP)
500     #
501
502     if args["gui"]:
503         mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
504         mySessionServ.setpath(modules_list,modules_root_dir)
505         mySessionServ.run()
506
507     #
508     # Launch Registry Server,
509     # and wait until it is registered in naming service
510     #
511
512     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
513         myServer=RegistryServer(args)
514         myServer.run()
515         if sys.platform == "win32":
516           clt.waitNS("/Registry")
517         else:
518           clt.waitNSPID("/Registry",myServer.PID)
519
520     #
521     # Launch Catalog Server,
522     # and wait until it is registered in naming service
523     #
524
525     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
526         cataServer=CatalogServer(args)
527         cataServer.setpath(modules_list,modules_root_dir)
528         cataServer.run()
529         import SALOME_ModuleCatalog
530         if sys.platform == "win32":
531           clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
532         else:
533           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
534
535     #
536     # Launch SalomeDS Server,
537     # and wait until it is registered in naming service
538     #
539
540     #print "ARGS = ",args
541     if ('study' not in args['embedded']) | (args["gui"] == 0):
542         print "RunStudy"
543         myServer=SalomeDSServer(args)
544         myServer.run()
545         if sys.platform == "win32":
546           clt.waitNS("/myStudyManager")
547         else:
548           clt.waitNSPID("/myStudyManager",myServer.PID)
549
550     #
551     # Launch LauncherServer
552     #
553
554     myCmServer = LauncherServer(args)
555     myCmServer.setpath(modules_list,modules_root_dir)
556     myCmServer.run()
557
558     #
559     # Launch ConnectionManagerServer
560     #
561
562     myConnectionServer = ConnectionManagerServer(args)
563     myConnectionServer.run()
564
565
566     from Utils_Identity import getShortHostName
567
568     if os.getenv("HOSTNAME") == None:
569         if os.getenv("HOST") == None:
570             os.environ["HOSTNAME"]=getShortHostName()
571         else:
572             os.environ["HOSTNAME"]=os.getenv("HOST")
573
574     theComputer = getShortHostName()
575
576     #
577     # Launch local C++ Container (FactoryServer),
578     # and wait until it is registered in naming service
579     #
580
581     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
582         myServer=ContainerCPPServer(args)
583         myServer.run()
584         if sys.platform == "win32":
585           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
586         else:
587           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
588
589     #
590     # Launch local Python Container (FactoryServerPy),
591     # and wait until it is registered in naming service
592     #
593
594     if 'pyContainer' in args['standalone']:
595         raise Exception('Python containers no longer supported')
596
597     #
598     # Wait until Session Server is registered in naming service
599     #
600
601     if args["gui"]:
602 ##----------------
603         import Engines
604         import SALOME
605         import SALOMEDS
606         import SALOME_ModuleCatalog
607         import SALOME_Session_idl
608         if sys.platform == "win32":
609           session=clt.waitNS("/Kernel/Session",SALOME.Session)
610         else:
611           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
612         args["session_object"] = session
613     end_time = os.times()
614     if verbose(): print
615     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
616                                                          - init_time[4])
617
618     # ASV start GUI without Loader
619     #if args['gui']:
620     #    session.GetInterface()
621
622     #
623     # additionnal external python interpreters
624     #
625     nbaddi=0
626
627     try:
628         if 'interp' in args:
629             nbaddi = args['interp']
630     except:
631         import traceback
632         traceback.print_exc()
633         print "-------------------------------------------------------------"
634         print "-- to get an external python interpreter:runSalome --interp=1"
635         print "-------------------------------------------------------------"
636
637     if verbose(): print "additional external python interpreters: ", nbaddi
638     if nbaddi:
639         for i in range(nbaddi):
640             print "i=",i
641             anInterp=InterpServer(args)
642             anInterp.run()
643
644     # set PYTHONINSPECT variable (python interpreter in interactive mode)
645     if args['pinter']:
646         os.environ["PYTHONINSPECT"]="1"
647         try:
648             import readline
649         except ImportError:
650             pass
651
652     return clt
653
654 # -----------------------------------------------------------------------------
655
656 def useSalome(args, modules_list, modules_root_dir):
657     """
658     Launch all SALOME servers requested by args,
659     save list of process, give info to user,
660     show registered objects in Naming Service.
661     """
662     global process_id
663
664     clt=None
665     try:
666         clt = startSalome(args, modules_list, modules_root_dir)
667     except:
668         import traceback
669         traceback.print_exc()
670         print
671         print
672         print "--- Error during Salome launch ---"
673
674     #print process_id
675
676     from addToKillList import addToKillList
677     from killSalomeWithPort import getPiDict
678
679     filedict = getPiDict(args['port'])
680     for pid, cmd in process_id.items():
681         addToKillList(pid, cmd, args['port'])
682         pass
683
684     if verbose(): print """
685     Saving of the dictionary of Salome processes in %s
686     To kill SALOME processes from a console (kill all sessions from all ports):
687       python killSalome.py
688     To kill SALOME from the present interpreter, if it is not closed :
689       killLocalPort()      --> kill this session
690                                (use CORBA port from args of runSalome)
691       givenPortKill(port)  --> kill a specific session with given CORBA port
692       killAllPorts()       --> kill all sessions
693
694     runSalome, with --killall option, starts with killing
695     the processes resulting from the previous execution.
696     """%filedict
697
698     #
699     #  Print Naming Service directory list
700     #
701
702     if clt != None:
703         if verbose():
704             print
705             print " --- registered objects tree in Naming Service ---"
706             clt.showNS()
707             pass
708
709         if not args['gui'] or not args['session_gui']:
710             if args['shutdown_servers']:
711                 class __utils__(object):
712                     def __init__(self, port):
713                         self.port = port
714                         import killSalomeWithPort
715                         self.killSalomeWithPort = killSalomeWithPort
716                         return
717                     def __del__(self):
718                         self.killSalomeWithPort.killMyPort(self.port)
719                         return
720                     pass
721                 args['shutdown_servers'] = __utils__(args['port'])
722                 pass
723             pass
724
725         # run python scripts, passed as command line arguments
726         toimport = []
727         if args.has_key('pyscript'):
728             if args.has_key('gui') and args.has_key('session_gui'):
729                 if not args['gui'] or not args['session_gui']:
730                     toimport = args['pyscript']
731
732         command = formatScriptsAndArgs(toimport)
733         if command:
734             proc = subprocess.Popen(command, shell=True)
735             proc.wait()
736
737     return clt
738
739 def execScript(script_path):
740     print 'executing', script_path
741     sys.path.insert(0, os.path.dirname(script_path))
742     execfile(script_path,globals())
743     del sys.path[0]
744
745 # -----------------------------------------------------------------------------
746
747 def registerEnv(args, modules_list, modules_root_dir):
748     """
749     Register args, modules_list, modules_root_dir in a file
750     for further use, when SALOME is launched embedded in an other application.
751     """
752     if sys.platform == "win32":
753       fileEnv = os.getenv('TEMP')
754     else:
755       fileEnv = '/tmp/'
756
757     fileEnv += os.getenv('USER') + "_" + str(args['port']) \
758             + '_' + args['appname'].upper() + '_env'
759     fenv=open(fileEnv,'w')
760     pickle.dump((args, modules_list, modules_root_dir),fenv)
761     fenv.close()
762     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
763
764 # -----------------------------------------------------------------------------
765
766 def no_main():
767     """Salome Launch, when embedded in other application"""
768     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
769     fenv=open(fileEnv,'r')
770     args, modules_list, modules_root_dir = pickle.load(fenv)
771     fenv.close()
772     kill_salome(args)
773     PortManager.start_server(nbSimultaneous=25, timeout=10)
774     from searchFreePort import searchFreePort
775     searchFreePort(args, 0)
776     clt = useSalome(args, modules_list, modules_root_dir)
777     return clt
778
779 # -----------------------------------------------------------------------------
780
781 def main():
782     """Salome launch as a main application"""
783
784     ### TEMP >>> ###
785     if not os.getenv("OMNIORB_USER_PATH"):
786         homePath = os.path.realpath(os.path.expanduser('~'))
787         #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
788         defaultOmniorbUserPath = homePath
789         if os.getenv("APPLI"):
790             defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
791         os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
792         pass
793     ### <<< TEMP ###
794
795     from salome_utils import getHostName
796     print "runSalome running on %s" % getHostName()
797     args, modules_list, modules_root_dir = setenv.get_config()
798
799     kill_salome(args)
800     save_config = True
801     if args.has_key('save_config'):
802         save_config = args['save_config']
803     # --
804     test = True
805     if args['wake_up_session']:
806         test = False
807         pass
808     if test:
809         PortManager.start_server(nbSimultaneous=25, timeout=10)
810         from searchFreePort import searchFreePort
811         searchFreePort(args, save_config, args.get('useport'))
812         pass
813     # --
814     #setenv.main()
815     setenv.set_env(args, modules_list, modules_root_dir)
816     clt = useSalome(args, modules_list, modules_root_dir)
817     return clt,args
818
819 # -----------------------------------------------------------------------------
820
821 def foreGround(clt, args):
822     # --
823     if "session_object" not in args:
824         return
825     session = args["session_object"]
826     # --
827     # Wait until gui is arrived
828     # tmax = nbtot * dt
829     # --
830     gui_detected = False
831     dt = 0.1
832     nbtot = 100
833     nb = 0
834     while 1:
835         try:
836             status = session.GetStatSession()
837             gui_detected = status.activeGUI
838         except:
839             pass
840         if gui_detected:
841             break
842         from time import sleep
843         sleep(dt)
844         nb += 1
845         if nb == nbtot:
846             break
847         pass
848     # --
849     if not gui_detected:
850         return
851     # --
852     from salome_utils import getPortNumber
853     port = getPortNumber()
854     # --
855     server = Server({})
856     if sys.platform == "win32":
857       server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
858     else:
859       server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
860     server.run()
861     # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
862     # --
863     dt = 1.0
864     try:
865         while 1:
866             try:
867                 status = session.GetStatSession()
868                 assert status.activeGUI
869             except:
870                 break
871             from time import sleep
872             sleep(dt)
873             pass
874         pass
875     except KeyboardInterrupt:
876         from killSalomeWithPort import killMyPort
877         killMyPort(port)
878         pass
879     return
880 #
881
882 def runSalome():
883     import user
884     clt,args = main()
885     # --
886     test = args['gui'] and args['session_gui']
887     test = test or args['wake_up_session']
888     # --
889     # The next test covers the --pinter option or var PYTHONINSPECT setted
890     # --
891     test = test and not os.environ.get('PYTHONINSPECT')
892     # --
893     # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
894     # --
895     try:
896         from ctypes import POINTER, c_int, cast, pythonapi
897         iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
898         test = test and not iflag_ptr.contents.value
899     except:
900         pass
901     # --
902     test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
903     test = test and args['foreground']
904     # --
905     if test:
906         foreGround(clt, args)
907         pass
908     # --
909     pass
910 #
911
912 # -----------------------------------------------------------------------------
913
914 if __name__ == "__main__":
915     runSalome()
916 #