Salome HOME
Attune getScriptsAndArgs() function:
[modules/kernel.git] / bin / salomeLauncherUtils.py
1 #! /usr/bin/env python
2
3 import os
4 import sys
5 import glob
6 import subprocess
7 import re
8
9 """
10 Define a specific exception class to manage exceptions related to SalomeRunner
11 """
12 class SalomeRunnerException(Exception):
13   """Report error messages to the user interface of SalomeRunner."""
14 #
15
16 def __listDirectory(path):
17   allFiles = []
18   for root, dirs, files in os.walk(path):
19     configFileNames = glob.glob(os.path.join(root,'*.cfg')) + glob.glob(os.path.join(root,'*.sh'))
20     allFiles += configFileNames
21   return allFiles
22 #
23
24 def __getConfigFileNamesDefault():
25   absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
26   if not absoluteAppliPath:
27     return []
28
29   envdDir = absoluteAppliPath + '/env.d'
30   if not os.path.isdir(envdDir):
31     return []
32
33   return __listDirectory(envdDir)
34 #
35
36 def getConfigFileNames(args, checkExistence=False):
37   # special case: configuration files are provided by user
38   # Search for command-line argument(s) --config=file1,file2,..., filen
39   # Search for command-line argument(s) --config=dir1,dir2,..., dirn
40   configOptionPrefix = "--config="
41   configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
42
43   if len(configArgs) == 0:
44     return __getConfigFileNamesDefault(), args, []
45
46   args = [ x for x in args if not x.startswith(configOptionPrefix) ]
47   allLists = [ x.replace(configOptionPrefix, '') for x in configArgs ]
48
49   configFileNames = []
50   unexisting = []
51   for currentList in allLists:
52     elements = currentList.split(',')
53     for elt in elements:
54       elt = os.path.realpath(os.path.expanduser(elt))
55       if os.path.isdir(elt):
56         configFileNames += __listDirectory(elt)
57       else:
58         if checkExistence and not os.path.isfile(elt):
59           unexisting += [elt]
60         else:
61           configFileNames += [elt]
62
63   return configFileNames, args, unexisting
64 #
65
66 # Return an array of dictionaries {script_name: [list_of_its_args]}
67 def getScriptsAndArgs(args=[]):
68   # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
69   scriptArgs = []
70   currentKey = None
71   argsPrefix = "args:"
72   callPython = False
73   currentScript = None
74
75   for i in range(len(args)):
76     elt = args[i]
77
78     if elt.startswith(argsPrefix):
79       if not currentKey or callPython:
80         raise SalomeRunnerException("args list must follow corresponding script file in command line.")
81       elt = elt.replace(argsPrefix, '')
82       scriptArgs[len(scriptArgs)-1][currentKey] = elt.split(",")
83       currentKey = None
84       callPython = False
85     elif elt.startswith("python"):
86       callPython = True
87     elif os.path.isfile(elt) or os.path.isfile(elt+".py"):
88       if elt[-4:] != ".hdf":
89         if elt[-3:] == ".py":
90           currentScript = os.path.abspath(elt)
91         elif os.path.isfile(elt+".py"):
92           currentScript = os.path.abspath(elt+".py")
93         else:
94           currentScript = os.path.abspath(elt) # python script not necessary has .py extension
95         pass
96       if currentScript and callPython:
97         currentKey = "python "+currentScript
98         scriptArgs.append({currentKey:[]})
99         callPython = False
100       elif currentScript:
101         if not os.access(currentScript, os.X_OK):
102           currentKey = "python "+currentScript
103           scriptArgs.append({currentKey:[]})
104         else:
105           ispython = False
106           try:
107             fn = open(currentScript)
108             for i in xrange(10): # read only 10 first lines 
109               ln = fn.readline()
110               if re.search("#!.*python"): 
111                 ispython = True
112                 break
113               pass
114             fn.close()
115           except:
116             pass
117           if not ispython and currentScript[-3:] == ".py":
118             currentKey = "python "+currentScript
119           else:
120             currentKey = currentScript
121             pass
122           scriptArgs.append({currentKey:[]})
123   # end for loop
124   return scriptArgs
125 #
126
127 # Formatting scripts and args as a Bash-like command-line:
128 # script1.py [args] ; script2.py [args] ; ...
129 def formatScriptsAndArgs(scriptArgs=[]):
130     commands = []
131     for sc_dict in scriptArgs:
132       for script, sc_args in sc_dict.items(): # single entry
133         cmd = script
134         if sc_args:
135           cmd = cmd + " " + " ".join(sc_args)
136         commands.append(cmd)
137
138     command = "; ".join(["%s"%x for x in commands])
139     return command
140 #
141
142 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a the folder in which
143 # SALOME will write omniOrb configuration files.
144 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
145 # an exception is raised if check fails. It allows users for choosing a specific folder.
146 # Else the function sets OMNIORB_USER_PATH this way:
147 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
148 #   The function does not check USERS folder existence or wrute access. This folder
149 #   must exist ; this is the case if SALOME virtual application has been create using
150 #   appli_gen.py script.
151 # - Else OMNIORB_USER_PATH is set to user home directory.
152 def setOmniOrbUserPath():
153   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
154   if omniorbUserPath:
155     if not os.access(omniorbUserPath, os.W_OK):
156       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
157     pass
158   else:
159     homePath = os.path.realpath(os.path.expanduser('~'))
160     #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
161     defaultOmniorbUserPath = homePath
162     if os.getenv("APPLI"):
163       defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
164       pass
165     os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
166 #