1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2013 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.
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 if sys.platform == "win32":
213 # for Windows the home directory is detected in the following way:
214 # 1. try USERPROFILE env variable
215 # 2. try combination of HOMEDRIVE and HOMEPATH env variables
216 # 3. try HOME env variable
217 # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used
218 dir = os.getenv("USERPROFILE")
219 if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
220 dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
222 dir = os.getenv("HOME")
225 # for Linux: use HOME variable
226 dir = os.getenv("HOME")
233 Get directory to be used for the temporary files.
236 if sys.platform == "win32":
237 # for Windows: temporarily using home directory for tmp files;
238 # to be replaced with TEMP environment variable later...
239 dir = os.getenv("HOME")
241 # for Linux: use /tmp/logs/{user} folder
242 dir = os.path.join( '/tmp', 'logs', getUserName() )
248 def generateFileName( dir, prefix = None, suffix = None, extension = None,
249 unique = False, separator = "_", hidden = False, **kwargs ):
251 Generate file name by sepecified parameters. If necessary, file name
252 can be generated to be unique.
255 - dir : directory path
256 - prefix : file prefix (not added by default)
257 - suffix : file suffix (not added by default)
258 - extension : file extension (not added by default)
259 - unique : if this parameter is True, the unique file name is generated:
260 in this case, if the file with the generated name already exists
261 in the <dir> directory, an integer suffix is added to the end of the
262 file name. This parameter is False by default.
263 - separator : separator of the words ('_' by default)
264 - hidden : if this parameter is True, the file name is prepended by . (dot)
265 symbol. This parameter is False by default.
267 Other keyword parameters are:
268 - with_username : 'add user name' flag/option:
269 * boolean value can be passed to determine user name automatically
270 * string value to be used as user name
271 - with_hostname : 'add host name' flag/option:
272 * boolean value can be passed to determine host name automatically
273 * string value to be used as host name
274 - with_port : 'add port number' flag/option:
275 * boolean value can be passed to determine port number automatically
276 * string value to be used as port number
277 - with_app : 'add application name' flag/option:
278 * boolean value can be passed to determine application name automatically
279 * string value to be used as application name
280 All <with_...> parameters are optional.
282 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
283 from launchConfigureParser import verbose
286 if separator is None:
290 separator = str( separator )
292 # prefix (if specified)
293 if prefix is not None:
294 filename.append( str( prefix ) )
296 # additional keywords
297 ### check unsupported parameters
299 if kw not in supported and verbose():
300 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
303 ### process supported keywords
305 if kw not in kwargs: continue
307 if kw == 'with_username':
310 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
313 # user name given as parameter
314 filename.append( kwargs[kw] )
318 elif kw == 'with_hostname':
321 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
324 # host name given as parameter
325 filename.append( kwargs[kw] )
329 elif kw == 'with_port':
332 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
335 # port number given as parameter
336 filename.append( str( kwargs[kw] ) )
340 elif kw == 'with_app':
342 # auto application name ?
343 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
346 # application name given as parameter
347 filename.append( kwargs[kw] )
351 # suffix (if specified)
352 if suffix is not None:
353 filename.append( str( suffix ) )
355 # raise an exception if file name is empty
357 raise Exception("Empty file name")
359 if extension is not None and extension.startswith("."): extension = extension[1:]
362 name = separator.join( filename )
363 if hidden: name = "." + name # add dot for hidden files
364 if extension: name = name + "." + str( extension ) # add extension if defined
365 name = os.path.join( dir, name )
367 # create unique file name
369 while os.path.exists( name ):
371 name = separator.join( filename ) + separator + str( index )
372 if hidden: name = "." + name # add dot for hidden files
373 if extension: name = name + "." + str( extension ) # add extension if defined
374 name = os.path.join( dir, name )
377 return os.path.normpath(name)
381 def makeTmpDir( path, mode=0777 ):
383 Make temporary directory with the specified path.
384 If the directory exists then clear its contents.
387 - path : absolute path to the directory to be created.
391 if os.path.exists( path ):
393 if sys.platform == "win32":
394 os.system( "rmdir /S /Q " + '"' + path + '"' )
395 os.system( "mkdir " + '"' + path + '"' )
397 os.system( "rm -rf " + path + "/*" )
399 dirs = path.split("/")
401 if not dirs[0]: shift1 = 1
402 if dirs[-1]: shift2 = 1
403 for i in range(1+shift1,len(dirs)+shift2):
404 p = "/".join(dirs[:i])
413 def uniteFiles( src_file, dest_file ):
415 Unite contents of the source file with contents of the destination file
416 and put result of the uniting to the destination file.
417 If the destination file does not exist then the source file is simply
421 - src_file : absolute path to the source file
422 - dest_file : absolute path to the destination file
426 if not os.path.exists( src_file ):
430 if os.path.exists( dest_file ):
431 # add a symbol of new line to contents of the destination file (just in case)
432 dest = open( dest_file, 'r' )
433 dest_lines = dest.readlines()
436 dest_lines.append( "\n" )
438 dest = open( dest_file, 'w' )
439 dest.writelines( dest_lines )
443 if sys.platform == "win32":
444 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
446 command = "cat " + src_file + " >> " + dest_file
451 if sys.platform == "win32":
452 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
454 command = "cp " + src_file + " " + dest_file
466 Get verbosity level. Default verbosity level is specified via the environment variable
467 SALOME_VERBOSE, e.g.:
468 [bash %] export SALOME_VERBOSE=1
469 The function setVerbose() can be used to change verbosity level explicitly.
472 # verbose has already been called
473 if _verbose is not None:
477 from os import getenv
478 _verbose = int(getenv('SALOME_VERBOSE'))
485 def setVerbose(level):
487 Change verbosity level. The function verbose() can be used to get current verbosity level.