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.
54 Check if specified parameter represents boolean value and returns its value.
55 String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
57 If <arg> does not represent a boolean, an exception is raised.
60 if type( arg ) == types.BooleanType :
62 elif type( arg ) == types.StringType :
63 v = str( arg ).lower()
64 if v in [ "yes", "y", "true" ]: return True
65 elif v in [ "no", "n", "false" ]: return False
67 raise Exception("Not boolean value")
73 Get omniORB current configuration.
74 Returns a list of three values: [ orb_version, host_name, port_number ].
76 The information is retrieved from the omniORB configuration file defined
77 by the OMNIORB_CONFIG environment variable.
78 If omniORB configuration file can not be accessed, a list of three empty
84 f = open( os.getenv( "OMNIORB_CONFIG" ) )
87 regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
92 if m.group(1) is None:
111 def getHostFromORBcfg():
113 Get current omniORB host.
115 return getORBcfgInfo()[1]
118 def getPortFromORBcfg():
120 Get current omniORB port.
122 return getORBcfgInfo()[2]
129 1. try USER environment variable (USERNAME on windows)
130 2. if fails, return 'unknown' as default user name
133 if sys.platform == "win32":
134 return os.getenv("USERNAME", "unknown")
136 return os.getenv("USER", "unknown")
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
150 host = socket.gethostname()
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
161 def getShortHostName():
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
170 return getHostName().split('.')[0]
173 return "unknown" # 'unknown' is default host name
179 Get application name:
180 1. try APPNAME environment variable
181 2. if fails, return 'SALOME' as default application name
184 return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
188 def getPortNumber(use_default=True):
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)
197 return int( os.getenv( "NSPORT" ) )
201 port = int( getPortFromORBcfg() )
202 if port is not None: return port
205 if use_default: return 2809 # '2809' is default port number
215 return os.path.realpath(os.path.expanduser('~'))
220 Get directory to be used for the log files.
223 return os.path.join(getTmpDir(), "logs", getUserName())
228 Get directory to be used for the temporary files.
231 f = tempfile.NamedTemporaryFile()
232 tmpdir = os.path.dirname(f.name)
237 def generateFileName( dir, prefix = None, suffix = None, extension = None,
238 unique = False, separator = "_", hidden = False, **kwargs ):
240 Generate file name by sepecified parameters. If necessary, file name
241 can be generated to be unique.
244 - dir : directory path
245 - prefix : file prefix (not added by default)
246 - suffix : file suffix (not added by default)
247 - extension : file extension (not added by default)
248 - unique : if this parameter is True, the unique file name is generated:
249 in this case, if the file with the generated name already exists
250 in the <dir> directory, an integer suffix is added to the end of the
251 file name. This parameter is False by default.
252 - separator : separator of the words ('_' by default)
253 - hidden : if this parameter is True, the file name is prepended by . (dot)
254 symbol. This parameter is False by default.
256 Other keyword parameters are:
257 - with_username : 'add user name' flag/option:
258 * boolean value can be passed to determine user name automatically
259 * string value to be used as user name
260 - with_hostname : 'add host name' flag/option:
261 * boolean value can be passed to determine host name automatically
262 * string value to be used as host name
263 - with_port : 'add port number' flag/option:
264 * boolean value can be passed to determine port number automatically
265 * string value to be used as port number
266 - with_app : 'add application name' flag/option:
267 * boolean value can be passed to determine application name automatically
268 * string value to be used as application name
269 All <with_...> parameters are optional.
271 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
272 from launchConfigureParser import verbose
275 if separator is None:
279 separator = str( separator )
281 # prefix (if specified)
282 if prefix is not None:
283 filename.append( str( prefix ) )
285 # additional keywords
286 ### check unsupported parameters
288 if kw not in supported and verbose():
289 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
292 ### process supported keywords
294 if kw not in kwargs: continue
296 if kw == 'with_username':
299 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
302 # user name given as parameter
303 filename.append( kwargs[kw] )
307 elif kw == 'with_hostname':
310 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
313 # host name given as parameter
314 filename.append( kwargs[kw] )
318 elif kw == 'with_port':
321 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
324 # port number given as parameter
325 filename.append( str( kwargs[kw] ) )
329 elif kw == 'with_app':
331 # auto application name ?
332 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
335 # application name given as parameter
336 filename.append( kwargs[kw] )
340 # suffix (if specified)
341 if suffix is not None:
342 filename.append( str( suffix ) )
344 # raise an exception if file name is empty
346 raise Exception("Empty file name")
348 if extension is not None and extension.startswith("."): extension = extension[1:]
351 name = separator.join( filename )
352 if hidden: name = "." + name # add dot for hidden files
353 if extension: name = name + "." + str( extension ) # add extension if defined
354 name = os.path.join( dir, name )
356 # create unique file name
358 while os.path.exists( name ):
360 name = separator.join( filename ) + separator + str( index )
361 if hidden: name = "." + name # add dot for hidden files
362 if extension: name = name + "." + str( extension ) # add extension if defined
363 name = os.path.join( dir, name )
366 return os.path.normpath(name)
370 def makeTmpDir( path, mode=0777 ):
372 Make temporary directory with the specified path.
373 If the directory exists then clear its contents.
376 - path : absolute path to the directory to be created.
380 if os.path.exists( path ):
382 if sys.platform == "win32":
383 os.system( "rmdir /S /Q " + '"' + path + '"' )
384 os.system( "mkdir " + '"' + path + '"' )
386 os.system( "rm -rf " + path + "/*" )
388 dirs = path.split("/")
390 if not dirs[0]: shift1 = 1
391 if dirs[-1]: shift2 = 1
392 for i in range(1+shift1,len(dirs)+shift2):
393 p = "/".join(dirs[:i])
402 def uniteFiles( src_file, dest_file ):
404 Unite contents of the source file with contents of the destination file
405 and put result of the uniting to the destination file.
406 If the destination file does not exist then the source file is simply
410 - src_file : absolute path to the source file
411 - dest_file : absolute path to the destination file
415 if not os.path.exists( src_file ):
419 if os.path.exists( dest_file ):
420 # add a symbol of new line to contents of the destination file (just in case)
421 dest = open( dest_file, 'r' )
422 dest_lines = dest.readlines()
425 dest_lines.append( "\n" )
427 dest = open( dest_file, 'w' )
428 dest.writelines( dest_lines )
432 if sys.platform == "win32":
433 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
435 command = "cat " + src_file + " >> " + dest_file
440 if sys.platform == "win32":
441 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
443 command = "cp " + src_file + " " + dest_file
455 Get verbosity level. Default verbosity level is specified via the environment variable
456 SALOME_VERBOSE, e.g.:
457 [bash %] export SALOME_VERBOSE=1
458 The function setVerbose() can be used to change verbosity level explicitly.
461 # verbose has already been called
462 if _verbose is not None:
466 from os import getenv
467 _verbose = int(getenv('SALOME_VERBOSE'))
475 def setVerbose(level):
477 Change verbosity level. The function verbose() can be used to get current verbosity level.