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