]> SALOME platform Git repositories - modules/kernel.git/blob - bin/salome_utils.py
Salome HOME
merge from branch BR_V5_DEV
[modules/kernel.git] / bin / salome_utils.py
1 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22 # ---
23 # File   : salome_utils.py
24 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
25 # ---
26 #
27 """
28 Set of utility functions used by SALOME python scripts.
29 """
30
31 #
32 # Exported functions
33 #
34 __all__ = [
35     'getORBcfgInfo',
36     'getHostFromORBcfg',
37     'getPortFromORBcfg',
38     'getUserName',
39     'getHostName',
40     'getShortHostName',
41     'getAppName',
42     'getPortNumber',
43     'getTmpDir',
44     'generateFileName',
45     ]
46
47 # ---
48
49 def _try_bool( arg ):
50     """
51     Check if specified parameter represents boolean value and returns its value.
52     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
53     are supported.
54     If <arg> does not represent a boolean, an exception is raised.
55     """
56     import types
57     if type( arg ) == types.BooleanType  :
58         return arg
59     elif type( arg ) == types.StringType  :
60         v = str( arg ).lower()
61         if   v in [ "yes", "y", "true"  ]: return True
62         elif v in [ "no",  "n", "false" ]: return False
63         pass
64     raise Exception("Not boolean value")
65
66 # ---
67
68 def getORBcfgInfo():
69     """
70     Get omniORB current configuration.
71     Returns a list of three values: [ orb_version, host_name, port_number ].
72     
73     The information is retrieved from the omniORB configuration file defined
74     by the OMNIORB_CONFIG environment variable.
75     If omniORB configuration file can not be accessed, a list of three empty
76     strings is returned.
77     """
78     import os, re
79     ret = [ "", "", "" ]
80     try:
81         f = open( os.getenv( "OMNIORB_CONFIG" ) )
82         lines = f.readlines()
83         f.close()
84         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
85         for l in lines:
86             try:
87                 m = regvar.match( l )
88                 if m:
89                     if m.group(1) is None:
90                         ret[0] = "4"
91                     else:
92                         ret[0] = "3"
93                         pass
94                     ret[1] = m.group(2)
95                     ret[2] = m.group(3)
96                     break
97                 pass
98             except:
99                 pass
100             pass
101         pass
102     except:
103         pass
104     return ret
105
106 # ---
107
108 def getHostFromORBcfg():
109     """
110     Get current omniORB host.
111     """
112     return getORBcfgInfo()[1]
113 # ---
114
115 def getPortFromORBcfg():
116     """
117     Get current omniORB port.
118     """
119     return getORBcfgInfo()[2]
120
121 # ---
122
123 def getUserName():
124     """
125     Get user name:
126     1. try USER environment variable
127     2. if fails, return 'unknown' as default user name
128     """
129     import os
130     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
131
132 # ---
133
134 def getHostName():
135     """
136     Get host name:
137     1. try socket python module gethostname() function
138     2. if fails, try HOSTNAME environment variable
139     3. if fails, try HOST environment variable
140     4. if fails, return 'unknown' as default host name
141     """
142     import os
143     try:
144         import socket
145         host = socket.gethostname()
146     except:
147         host = None
148         pass
149     if not host: host = os.getenv("HOSTNAME")
150     if not host: host = os.getenv("HOST")
151     if not host: host = "unknown"           # 'unknown' is default host name
152     return host
153
154 # ---
155
156 def getShortHostName():
157     """
158     Get short host name:
159     1. try socket python module gethostname() function
160     2. if fails, try HOSTNAME environment variable
161     3. if fails, try HOST environment variable
162     4. if fails, return 'unknown' as default host name
163     """
164     try:
165         return getHostName().split('.')[0]
166     except:
167         pass
168     return "unknown"           # 'unknown' is default host name
169     
170 # ---
171
172 def getAppName():
173     """
174     Get application name:
175     1. try APPNAME environment variable
176     2. if fails, return 'SALOME' as default application name
177     """
178     import os
179     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
180
181 # ---
182
183 def getPortNumber():
184     """
185     Get current naming server port number:
186     1. try NSPORT environment variable
187     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
188     2. if fails, return 2809 as default port number
189     """
190     import os
191     try:
192         return int( os.getenv( "NSPORT" ) )
193     except:
194         pass
195     port = getPortFromORBcfg()
196     if port is not None: return port
197     return 2809      # '2809' is default port number
198
199 # ---
200
201 def getTmpDir():
202     """
203     Get directory to be used for the temporary files.
204     """
205     import os, sys
206     if sys.platform == "win32":
207         # for Windows: temporarily using home directory for tmp files;
208         # to be replaced with TEMP environment variable later...
209         dir = os.getenv("HOME")
210     else:
211         # for Linux: use /tmp/logs/{user} folder
212         dir = os.path.join( '/tmp', 'logs', getUserName() )
213         pass
214     return dir
215
216 # ---
217
218 def generateFileName( dir, prefix = None, suffix = None, extension = None,
219                       unique = False, separator = "_", hidden = False, **kwargs ):
220     """
221     Generate file name by sepecified parameters. If necessary, file name
222     can be generated to be unique.
223
224     Parameters:
225     - dir       : directory path
226     - prefix    : file prefix (not added by default)
227     - suffix    : file suffix (not added by default)
228     - extension : file extension (not added by default)
229     - unique    : if this parameter is True, the unique file name is generated:
230     in this case, if the file with the generated name already exists
231     in the <dir> directory, an integer suffix is added to the end of the
232     file name. This parameter is False by default.
233     - separator : separator of the words ('_' by default)
234     - hidden    : if this parameter is True, the file name is prepended by . (dot)
235     symbol. This parameter is False by default.
236
237     Other keyword parameters are:
238     - with_username : 'add user name' flag/option:
239       * boolean value can be passed to determine user name automatically
240       * string value to be used as user name
241     - with_hostname : 'add host name' flag/option:
242       * boolean value can be passed to determine host name automatically
243       * string value to be used as host name
244     - with_port     : 'add port number' flag/option:
245       * boolean value can be passed to determine port number automatically
246       * string value to be used as port number
247     - with_app      : 'add application name' flag/option:
248       * boolean value can be passed to determine application name automatically
249       * string value to be used as application name
250     All <with_...> parameters are optional.
251     """
252     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
253     from launchConfigureParser import verbose
254     filename = []
255     # separator
256     if separator is None:
257         separator = ""
258         pass
259     else:
260         separator = str( separator )
261         pass
262     # prefix (if specified)
263     if prefix is not None:
264         filename.append( str( prefix ) )
265         pass
266     # additional keywords
267     ### check unsupported parameters
268     for kw in kwargs:
269         if kw not in supported and verbose():
270             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
271             pass
272         pass
273     ### process supported keywords
274     for kw in supported:
275         if kw not in kwargs: continue
276         ### user name
277         if kw == 'with_username':
278             try:
279                 # auto user name ?
280                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
281                 pass
282             except:
283                 # user name given as parameter
284                 filename.append( kwargs[kw] )
285                 pass
286             pass
287         ### host name
288         elif kw == 'with_hostname':
289             try:
290                 # auto host name ?
291                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
292                 pass
293             except:
294                 # host name given as parameter
295                 filename.append( kwargs[kw] )
296                 pass
297             pass
298         ### port number
299         elif kw == 'with_port':
300             try:
301                 # auto port number ?
302                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
303                 pass
304             except:
305                 # port number given as parameter
306                 filename.append( str( kwargs[kw] ) )
307                 pass
308             pass
309         ### application name
310         elif kw == 'with_app':
311             try:
312                 # auto application name ?
313                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
314                 pass
315             except:
316                 # application name given as parameter
317                 filename.append( kwargs[kw] )
318                 pass
319             pass
320         pass
321     # suffix (if specified)
322     if suffix is not None:
323         filename.append( str( suffix ) )
324         pass
325     # raise an exception if file name is empty
326     if not filename:
327         raise Exception("Empty file name")
328     #
329     if extension is not None and extension.startswith("."): extension = extension[1:]
330     #
331     import os
332     name = separator.join( filename )
333     if hidden: name = "." + name                       # add dot for hidden files
334     if extension: name = name + "." + str( extension ) # add extension if defined
335     name = os.path.join( dir, name )
336     if unique:
337         # create unique file name
338         index = 0
339         while os.path.exists( name ):
340             index = index + 1
341             name = separator.join( filename ) + separator + str( index )
342             if hidden: name = "." + name                       # add dot for hidden files
343             if extension: name = name + "." + str( extension ) # add extension if defined
344             name = os.path.join( dir, name )
345             pass
346         pass
347     return os.path.normpath(name)