1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 # File : salome_utils.py
23 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
26 ## @package salome_utils
27 # \brief Set of utility functions used by SALOME python scripts.
53 Check if specified parameter represents boolean value and returns its value.
54 String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
56 If <arg> does not represent a boolean, an exception is raised.
59 if type( arg ) == types.BooleanType :
61 elif type( arg ) == types.StringType :
62 v = str( arg ).lower()
63 if v in [ "yes", "y", "true" ]: return True
64 elif v in [ "no", "n", "false" ]: return False
66 raise Exception("Not boolean value")
72 Get omniORB current configuration.
73 Returns a list of three values: [ orb_version, host_name, port_number ].
75 The information is retrieved from the omniORB configuration file defined
76 by the OMNIORB_CONFIG environment variable.
77 If omniORB configuration file can not be accessed, a list of three empty
83 f = open( os.getenv( "OMNIORB_CONFIG" ) )
86 regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
91 if m.group(1) is None:
110 def getHostFromORBcfg():
112 Get current omniORB host.
114 return getORBcfgInfo()[1]
117 def getPortFromORBcfg():
119 Get current omniORB port.
121 return getORBcfgInfo()[2]
128 1. try USER environment variable
129 2. if fails, return 'unknown' as default user name
132 return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
139 1. try socket python module gethostname() function
140 2. if fails, try HOSTNAME environment variable
141 3. if fails, try HOST environment variable
142 4. if fails, return 'unknown' as default host name
147 host = socket.gethostname()
151 if not host: host = os.getenv("HOSTNAME")
152 if not host: host = os.getenv("HOST")
153 if not host: host = "unknown" # 'unknown' is default host name
158 def getShortHostName():
161 1. try socket python module gethostname() function
162 2. if fails, try HOSTNAME environment variable
163 3. if fails, try HOST environment variable
164 4. if fails, return 'unknown' as default host name
167 return getHostName().split('.')[0]
170 return "unknown" # 'unknown' is default host name
176 Get application name:
177 1. try APPNAME environment variable
178 2. if fails, return 'SALOME' as default application name
181 return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
185 def getPortNumber(use_default=True):
187 Get current naming server port number:
188 1. try NSPORT environment variable
189 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
190 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
194 return int( os.getenv( "NSPORT" ) )
198 port = int( getPortFromORBcfg() )
199 if port is not None: return port
202 if use_default: return 2809 # '2809' is default port number
212 return os.path.realpath(os.path.expanduser('~'))
217 Get directory to be used for the temporary files.
220 if sys.platform == "win32":
221 # for Windows: temporarily using home directory for tmp files;
222 # to be replaced with TEMP environment variable later...
223 dir = os.getenv("HOME")
225 # for Linux: use /tmp/logs/{user} folder
226 dir = os.path.join( '/tmp', 'logs', getUserName() )
232 def generateFileName( dir, prefix = None, suffix = None, extension = None,
233 unique = False, separator = "_", hidden = False, **kwargs ):
235 Generate file name by sepecified parameters. If necessary, file name
236 can be generated to be unique.
239 - dir : directory path
240 - prefix : file prefix (not added by default)
241 - suffix : file suffix (not added by default)
242 - extension : file extension (not added by default)
243 - unique : if this parameter is True, the unique file name is generated:
244 in this case, if the file with the generated name already exists
245 in the <dir> directory, an integer suffix is added to the end of the
246 file name. This parameter is False by default.
247 - separator : separator of the words ('_' by default)
248 - hidden : if this parameter is True, the file name is prepended by . (dot)
249 symbol. This parameter is False by default.
251 Other keyword parameters are:
252 - with_username : 'add user name' flag/option:
253 * boolean value can be passed to determine user name automatically
254 * string value to be used as user name
255 - with_hostname : 'add host name' flag/option:
256 * boolean value can be passed to determine host name automatically
257 * string value to be used as host name
258 - with_port : 'add port number' flag/option:
259 * boolean value can be passed to determine port number automatically
260 * string value to be used as port number
261 - with_app : 'add application name' flag/option:
262 * boolean value can be passed to determine application name automatically
263 * string value to be used as application name
264 All <with_...> parameters are optional.
266 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
267 from launchConfigureParser import verbose
270 if separator is None:
274 separator = str( separator )
276 # prefix (if specified)
277 if prefix is not None:
278 filename.append( str( prefix ) )
280 # additional keywords
281 ### check unsupported parameters
283 if kw not in supported and verbose():
284 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
287 ### process supported keywords
289 if kw not in kwargs: continue
291 if kw == 'with_username':
294 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
297 # user name given as parameter
298 filename.append( kwargs[kw] )
302 elif kw == 'with_hostname':
305 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
308 # host name given as parameter
309 filename.append( kwargs[kw] )
313 elif kw == 'with_port':
316 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
319 # port number given as parameter
320 filename.append( str( kwargs[kw] ) )
324 elif kw == 'with_app':
326 # auto application name ?
327 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
330 # application name given as parameter
331 filename.append( kwargs[kw] )
335 # suffix (if specified)
336 if suffix is not None:
337 filename.append( str( suffix ) )
339 # raise an exception if file name is empty
341 raise Exception("Empty file name")
343 if extension is not None and extension.startswith("."): extension = extension[1:]
346 name = separator.join( filename )
347 if hidden: name = "." + name # add dot for hidden files
348 if extension: name = name + "." + str( extension ) # add extension if defined
349 name = os.path.join( dir, name )
351 # create unique file name
353 while os.path.exists( name ):
355 name = separator.join( filename ) + separator + str( index )
356 if hidden: name = "." + name # add dot for hidden files
357 if extension: name = name + "." + str( extension ) # add extension if defined
358 name = os.path.join( dir, name )
361 return os.path.normpath(name)
365 def makeTmpDir( path, mode=0777 ):
367 Make temporary directory with the specified path.
368 If the directory exists then clear its contents.
371 - path : absolute path to the directory to be created.
375 if os.path.exists( path ):
377 if sys.platform == "win32":
378 os.system( "rmdir /S /Q " + '"' + path + '"' )
379 os.system( "mkdir " + '"' + path + '"' )
381 os.system( "rm -rf " + path + "/*" )
383 dirs = path.split("/")
385 if not dirs[0]: shift1 = 1
386 if dirs[-1]: shift2 = 1
387 for i in range(1+shift1,len(dirs)+shift2):
388 p = "/".join(dirs[:i])
397 def uniteFiles( src_file, dest_file ):
399 Unite contents of the source file with contents of the destination file
400 and put result of the uniting to the destination file.
401 If the destination file does not exist then the source file is simply
405 - src_file : absolute path to the source file
406 - dest_file : absolute path to the destination file
410 if not os.path.exists( src_file ):
414 if os.path.exists( dest_file ):
415 # add a symbol of new line to contents of the destination file (just in case)
416 dest = open( dest_file, 'r' )
417 dest_lines = dest.readlines()
420 dest_lines.append( "\n" )
422 dest = open( dest_file, 'w' )
423 dest.writelines( dest_lines )
427 if sys.platform == "win32":
428 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
430 command = "cat " + src_file + " >> " + dest_file
435 if sys.platform == "win32":
436 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
438 command = "cp " + src_file + " " + dest_file
450 Get verbosity level. Default verbosity level is specified via the environment variable
451 SALOME_VERBOSE, e.g.:
452 [bash %] export SALOME_VERBOSE=1
453 The function setVerbose() can be used to change verbosity level explicitly.
456 # verbose has already been called
457 if _verbose is not None:
461 from os import getenv
462 _verbose = int(getenv('SALOME_VERBOSE'))
469 def setVerbose(level):
471 Change verbosity level. The function verbose() can be used to get current verbosity level.