1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2011 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.
52 Check if specified parameter represents boolean value and returns its value.
53 String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
55 If <arg> does not represent a boolean, an exception is raised.
58 if type( arg ) == types.BooleanType :
60 elif type( arg ) == types.StringType :
61 v = str( arg ).lower()
62 if v in [ "yes", "y", "true" ]: return True
63 elif v in [ "no", "n", "false" ]: return False
65 raise Exception("Not boolean value")
71 Get omniORB current configuration.
72 Returns a list of three values: [ orb_version, host_name, port_number ].
74 The information is retrieved from the omniORB configuration file defined
75 by the OMNIORB_CONFIG environment variable.
76 If omniORB configuration file can not be accessed, a list of three empty
82 f = open( os.getenv( "OMNIORB_CONFIG" ) )
85 regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
90 if m.group(1) is None:
109 def getHostFromORBcfg():
111 Get current omniORB host.
113 return getORBcfgInfo()[1]
116 def getPortFromORBcfg():
118 Get current omniORB port.
120 return getORBcfgInfo()[2]
127 1. try USER environment variable
128 2. if fails, return 'unknown' as default user name
131 return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
138 1. try socket python module gethostname() function
139 2. if fails, try HOSTNAME environment variable
140 3. if fails, try HOST environment variable
141 4. if fails, return 'unknown' as default host name
146 host = socket.gethostname()
150 if not host: host = os.getenv("HOSTNAME")
151 if not host: host = os.getenv("HOST")
152 if not host: host = "unknown" # 'unknown' is default host name
157 def getShortHostName():
160 1. try socket python module gethostname() function
161 2. if fails, try HOSTNAME environment variable
162 3. if fails, try HOST environment variable
163 4. if fails, return 'unknown' as default host name
166 return getHostName().split('.')[0]
169 return "unknown" # 'unknown' is default host name
175 Get application name:
176 1. try APPNAME environment variable
177 2. if fails, return 'SALOME' as default application name
180 return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
184 def getPortNumber(use_default=True):
186 Get current naming server port number:
187 1. try NSPORT environment variable
188 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
189 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
193 return int( os.getenv( "NSPORT" ) )
196 port = getPortFromORBcfg()
197 if port is not None: return port
198 if use_default: return 2809 # '2809' is default port number
205 Get directory to be used for the temporary files.
208 if sys.platform == "win32":
209 # for Windows: temporarily using home directory for tmp files;
210 # to be replaced with TEMP environment variable later...
211 dir = os.getenv("HOME")
213 # for Linux: use /tmp/logs/{user} folder
214 dir = os.path.join( '/tmp', 'logs', getUserName() )
220 def generateFileName( dir, prefix = None, suffix = None, extension = None,
221 unique = False, separator = "_", hidden = False, **kwargs ):
223 Generate file name by sepecified parameters. If necessary, file name
224 can be generated to be unique.
227 - dir : directory path
228 - prefix : file prefix (not added by default)
229 - suffix : file suffix (not added by default)
230 - extension : file extension (not added by default)
231 - unique : if this parameter is True, the unique file name is generated:
232 in this case, if the file with the generated name already exists
233 in the <dir> directory, an integer suffix is added to the end of the
234 file name. This parameter is False by default.
235 - separator : separator of the words ('_' by default)
236 - hidden : if this parameter is True, the file name is prepended by . (dot)
237 symbol. This parameter is False by default.
239 Other keyword parameters are:
240 - with_username : 'add user name' flag/option:
241 * boolean value can be passed to determine user name automatically
242 * string value to be used as user name
243 - with_hostname : 'add host name' flag/option:
244 * boolean value can be passed to determine host name automatically
245 * string value to be used as host name
246 - with_port : 'add port number' flag/option:
247 * boolean value can be passed to determine port number automatically
248 * string value to be used as port number
249 - with_app : 'add application name' flag/option:
250 * boolean value can be passed to determine application name automatically
251 * string value to be used as application name
252 All <with_...> parameters are optional.
254 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
255 from launchConfigureParser import verbose
258 if separator is None:
262 separator = str( separator )
264 # prefix (if specified)
265 if prefix is not None:
266 filename.append( str( prefix ) )
268 # additional keywords
269 ### check unsupported parameters
271 if kw not in supported and verbose():
272 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
275 ### process supported keywords
277 if kw not in kwargs: continue
279 if kw == 'with_username':
282 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
285 # user name given as parameter
286 filename.append( kwargs[kw] )
290 elif kw == 'with_hostname':
293 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
296 # host name given as parameter
297 filename.append( kwargs[kw] )
301 elif kw == 'with_port':
304 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
307 # port number given as parameter
308 filename.append( str( kwargs[kw] ) )
312 elif kw == 'with_app':
314 # auto application name ?
315 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
318 # application name given as parameter
319 filename.append( kwargs[kw] )
323 # suffix (if specified)
324 if suffix is not None:
325 filename.append( str( suffix ) )
327 # raise an exception if file name is empty
329 raise Exception("Empty file name")
331 if extension is not None and extension.startswith("."): extension = extension[1:]
334 name = separator.join( filename )
335 if hidden: name = "." + name # add dot for hidden files
336 if extension: name = name + "." + str( extension ) # add extension if defined
337 name = os.path.join( dir, name )
339 # create unique file name
341 while os.path.exists( name ):
343 name = separator.join( filename ) + separator + str( index )
344 if hidden: name = "." + name # add dot for hidden files
345 if extension: name = name + "." + str( extension ) # add extension if defined
346 name = os.path.join( dir, name )
349 return os.path.normpath(name)
353 def makeTmpDir( path, mode=0777 ):
355 Make temporary directory with the specified path.
356 If the directory exists then clear its contents.
359 - path : absolute path to the directory to be created.
363 if os.path.exists( path ):
365 if sys.platform == "win32":
366 os.system( "rmdir /S /Q " + '"' + path + '"' )
367 os.system( "mkdir " + '"' + path + '"' )
369 os.system( "rm -rf " + path + "/*" )
371 dirs = path.split("/")
373 if not dirs[0]: shift1 = 1
374 if dirs[-1]: shift2 = 1
375 for i in range(1+shift1,len(dirs)+shift2):
376 p = "/".join(dirs[:i])
385 def uniteFiles( src_file, dest_file ):
387 Unite contents of the source file with contents of the destination file
388 and put result of the uniting to the destination file.
389 If the destination file does not exist then the source file is simply
393 - src_file : absolute path to the source file
394 - dest_file : absolute path to the destination file
398 if not os.path.exists( src_file ):
402 if os.path.exists( dest_file ):
403 # add a symbol of new line to contents of the destination file (just in case)
404 dest = open( dest_file, 'r' )
405 dest_lines = dest.readlines()
408 dest_lines.append( "\n" )
410 dest = open( dest_file, 'w' )
411 dest.writelines( dest_lines )
415 if sys.platform == "win32":
416 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
418 command = "cat " + src_file + " >> " + dest_file
423 if sys.platform == "win32":
424 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
426 command = "cp " + src_file + " " + dest_file
438 Get verbosity level. Default verbosity level is specified via the environment variable
439 SALOME_VERBOSE, e.g.:
440 [bash %] export SALOME_VERBOSE=1
441 The function setVerbose() can be used to change verbosity level explicitly.
444 # verbose has already been called
445 if _verbose is not None:
449 from os import getenv
450 _verbose = int(getenv('SALOME_VERBOSE'))
457 def setVerbose(level):
459 Change verbosity level. The function verbose() can be used to get current verbosity level.