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