Salome HOME
Porting to Python 2.6 - add coding page specification for Python scripts
[modules/kernel.git] / bin / salome_utils.py
1 #! /usr/bin/python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2008  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 # File   : salome_utils.py
26 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
27 # ---
28 #
29 ## @package salome_utils
30 # \brief Set of utility functions used by SALOME python scripts.
31 #
32 #
33
34 #
35 # Exported functions
36 #
37 __all__ = [
38     'getORBcfgInfo',
39     'getHostFromORBcfg',
40     'getPortFromORBcfg',
41     'getUserName',
42     'getHostName',
43     'getShortHostName',
44     'getAppName',
45     'getPortNumber',
46     'getTmpDir',
47     'generateFileName',
48     'makeTmpDir',
49     'uniteFiles',
50     ]
51
52 # ---
53
54 def _try_bool( arg ):
55     """
56     Check if specified parameter represents boolean value and returns its value.
57     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
58     are supported.
59     If <arg> does not represent a boolean, an exception is raised.
60     """
61     import types
62     if type( arg ) == types.BooleanType  :
63         return arg
64     elif type( arg ) == types.StringType  :
65         v = str( arg ).lower()
66         if   v in [ "yes", "y", "true"  ]: return True
67         elif v in [ "no",  "n", "false" ]: return False
68         pass
69     raise Exception("Not boolean value")
70
71 # ---
72
73 def getORBcfgInfo():
74     """
75     Get omniORB current configuration.
76     Returns a list of three values: [ orb_version, host_name, port_number ].
77     
78     The information is retrieved from the omniORB configuration file defined
79     by the OMNIORB_CONFIG environment variable.
80     If omniORB configuration file can not be accessed, a list of three empty
81     strings is returned.
82     """
83     import os, re
84     ret = [ "", "", "" ]
85     try:
86         f = open( os.getenv( "OMNIORB_CONFIG" ) )
87         lines = f.readlines()
88         f.close()
89         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
90         for l in lines:
91             try:
92                 m = regvar.match( l )
93                 if m:
94                     if m.group(1) is None:
95                         ret[0] = "4"
96                     else:
97                         ret[0] = "3"
98                         pass
99                     ret[1] = m.group(2)
100                     ret[2] = m.group(3)
101                     break
102                 pass
103             except:
104                 pass
105             pass
106         pass
107     except:
108         pass
109     return ret
110
111 # ---
112
113 def getHostFromORBcfg():
114     """
115     Get current omniORB host.
116     """
117     return getORBcfgInfo()[1]
118 # ---
119
120 def getPortFromORBcfg():
121     """
122     Get current omniORB port.
123     """
124     return getORBcfgInfo()[2]
125
126 # ---
127
128 def getUserName():
129     """
130     Get user name:
131     1. try USER environment variable
132     2. if fails, return 'unknown' as default user name
133     """
134     import os
135     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
136
137 # ---
138
139 def getHostName():
140     """
141     Get host name:
142     1. try socket python module gethostname() function
143     2. if fails, try HOSTNAME environment variable
144     3. if fails, try HOST environment variable
145     4. if fails, return 'unknown' as default host name
146     """
147     import os
148     try:
149         import socket
150         host = socket.gethostname()
151     except:
152         host = None
153         pass
154     if not host: host = os.getenv("HOSTNAME")
155     if not host: host = os.getenv("HOST")
156     if not host: host = "unknown"           # 'unknown' is default host name
157     return host
158
159 # ---
160
161 def getShortHostName():
162     """
163     Get short host name:
164     1. try socket python module gethostname() function
165     2. if fails, try HOSTNAME environment variable
166     3. if fails, try HOST environment variable
167     4. if fails, return 'unknown' as default host name
168     """
169     try:
170         return getHostName().split('.')[0]
171     except:
172         pass
173     return "unknown"           # 'unknown' is default host name
174     
175 # ---
176
177 def getAppName():
178     """
179     Get application name:
180     1. try APPNAME environment variable
181     2. if fails, return 'SALOME' as default application name
182     """
183     import os
184     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
185
186 # ---
187
188 def getPortNumber(use_default=True):
189     """
190     Get current naming server port number:
191     1. try NSPORT environment variable
192     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
193     2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
194     """
195     import os
196     try:
197         return int( os.getenv( "NSPORT" ) )
198     except:
199         pass
200     port = getPortFromORBcfg()
201     if port is not None: return port
202     if use_default: return 2809 # '2809' is default port number
203     return None
204
205 # ---
206
207 def getTmpDir():
208     """
209     Get directory to be used for the temporary files.
210     """
211     import os, sys
212     if sys.platform == "win32":
213         # for Windows: temporarily using home directory for tmp files;
214         # to be replaced with TEMP environment variable later...
215         dir = os.getenv("HOME")
216     else:
217         # for Linux: use /tmp/logs/{user} folder
218         dir = os.path.join( '/tmp', 'logs', getUserName() )
219         pass
220     return dir
221
222 # ---
223
224 def generateFileName( dir, prefix = None, suffix = None, extension = None,
225                       unique = False, separator = "_", hidden = False, **kwargs ):
226     """
227     Generate file name by sepecified parameters. If necessary, file name
228     can be generated to be unique.
229
230     Parameters:
231     - dir       : directory path
232     - prefix    : file prefix (not added by default)
233     - suffix    : file suffix (not added by default)
234     - extension : file extension (not added by default)
235     - unique    : if this parameter is True, the unique file name is generated:
236     in this case, if the file with the generated name already exists
237     in the <dir> directory, an integer suffix is added to the end of the
238     file name. This parameter is False by default.
239     - separator : separator of the words ('_' by default)
240     - hidden    : if this parameter is True, the file name is prepended by . (dot)
241     symbol. This parameter is False by default.
242
243     Other keyword parameters are:
244     - with_username : 'add user name' flag/option:
245       * boolean value can be passed to determine user name automatically
246       * string value to be used as user name
247     - with_hostname : 'add host name' flag/option:
248       * boolean value can be passed to determine host name automatically
249       * string value to be used as host name
250     - with_port     : 'add port number' flag/option:
251       * boolean value can be passed to determine port number automatically
252       * string value to be used as port number
253     - with_app      : 'add application name' flag/option:
254       * boolean value can be passed to determine application name automatically
255       * string value to be used as application name
256     All <with_...> parameters are optional.
257     """
258     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
259     from launchConfigureParser import verbose
260     filename = []
261     # separator
262     if separator is None:
263         separator = ""
264         pass
265     else:
266         separator = str( separator )
267         pass
268     # prefix (if specified)
269     if prefix is not None:
270         filename.append( str( prefix ) )
271         pass
272     # additional keywords
273     ### check unsupported parameters
274     for kw in kwargs:
275         if kw not in supported and verbose():
276             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
277             pass
278         pass
279     ### process supported keywords
280     for kw in supported:
281         if kw not in kwargs: continue
282         ### user name
283         if kw == 'with_username':
284             try:
285                 # auto user name ?
286                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
287                 pass
288             except:
289                 # user name given as parameter
290                 filename.append( kwargs[kw] )
291                 pass
292             pass
293         ### host name
294         elif kw == 'with_hostname':
295             try:
296                 # auto host name ?
297                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
298                 pass
299             except:
300                 # host name given as parameter
301                 filename.append( kwargs[kw] )
302                 pass
303             pass
304         ### port number
305         elif kw == 'with_port':
306             try:
307                 # auto port number ?
308                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
309                 pass
310             except:
311                 # port number given as parameter
312                 filename.append( str( kwargs[kw] ) )
313                 pass
314             pass
315         ### application name
316         elif kw == 'with_app':
317             try:
318                 # auto application name ?
319                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
320                 pass
321             except:
322                 # application name given as parameter
323                 filename.append( kwargs[kw] )
324                 pass
325             pass
326         pass
327     # suffix (if specified)
328     if suffix is not None:
329         filename.append( str( suffix ) )
330         pass
331     # raise an exception if file name is empty
332     if not filename:
333         raise Exception("Empty file name")
334     #
335     if extension is not None and extension.startswith("."): extension = extension[1:]
336     #
337     import os
338     name = separator.join( filename )
339     if hidden: name = "." + name                       # add dot for hidden files
340     if extension: name = name + "." + str( extension ) # add extension if defined
341     name = os.path.join( dir, name )
342     if unique:
343         # create unique file name
344         index = 0
345         while os.path.exists( name ):
346             index = index + 1
347             name = separator.join( filename ) + separator + str( index )
348             if hidden: name = "." + name                       # add dot for hidden files
349             if extension: name = name + "." + str( extension ) # add extension if defined
350             name = os.path.join( dir, name )
351             pass
352         pass
353     return os.path.normpath(name)
354
355 # ---
356
357 def makeTmpDir( path, mode=0777 ):
358     """
359     Make temporary directory with the specified path.
360     If the directory exists then clear its contents.
361
362     Parameters:
363     - path : absolute path to the directory to be created.
364     - mode : access mode
365     """
366     import os
367     if os.path.exists( path ):
368         import sys
369         if sys.platform == "win32":
370             os.system( "rmdir /S /Q " + '"' + path + '"' )
371             os.system( "mkdir " + '"' + path + '"' )
372         else:
373             os.system( "rm -rf " + path + "/*" )
374             pass
375         pass
376     else:
377         dirs = path.split("/")
378         shift1 = shift2 = 0
379         if not dirs[0]: shift1 = 1
380         if dirs[-1]: shift2 = 1
381         for i in range(1+shift1,len(dirs)+shift2):
382             p = "/".join(dirs[:i])
383             try:
384                 os.mkdir(p, mode)
385                 os.chmod(p, mode)
386             except:
387                 pass
388             pass
389         pass
390     pass
391
392 # ---
393
394 def uniteFiles( src_file, dest_file ):
395     """
396     Unite contents of the source file with contents of the destination file
397     and put result of the uniting to the destination file.
398     If the destination file does not exist then the source file is simply
399     copied to its path.
400
401     Parameters:
402     - src_file  : absolute path to the source file
403     - dest_file : absolute path to the destination file
404     """
405     import os
406
407     if not os.path.exists( src_file ):
408         return
409         pass
410
411     if os.path.exists( dest_file ):
412         # add a symbol of new line to contents of the destination file (just in case)
413         dest = open( dest_file, 'r' )
414         dest_lines = dest.readlines()
415         dest.close()
416
417         dest_lines.append( "\n" )
418
419         dest = open( dest_file, 'w' )
420         dest.writelines( dest_lines )
421         dest.close()
422
423         import sys
424         if sys.platform == "win32":
425             command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
426         else:
427             command = "cat " + src_file + " >> " + dest_file
428             pass
429         pass
430     else:
431         import sys
432         if sys.platform == "win32":
433             command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
434         else:
435             command = "cp " + src_file + " " + dest_file
436             pass
437         pass
438
439     os.system( command )