2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
5 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
25 # File : salome_utils.py
26 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
29 ## @package salome_utils
30 # \brief Set of utility functions used by SALOME python scripts.
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
59 If <arg> does not represent a boolean, an exception is raised.
62 if type( arg ) == types.BooleanType :
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
69 raise Exception("Not boolean value")
75 Get omniORB current configuration.
76 Returns a list of three values: [ orb_version, host_name, port_number ].
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
86 f = open( os.getenv( "OMNIORB_CONFIG" ) )
89 regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
94 if m.group(1) is None:
113 def getHostFromORBcfg():
115 Get current omniORB host.
117 return getORBcfgInfo()[1]
120 def getPortFromORBcfg():
122 Get current omniORB port.
124 return getORBcfgInfo()[2]
131 1. try USER environment variable
132 2. if fails, return 'unknown' as default user name
135 return os.getenv( "USER", "unknown" ) # 'unknown' is default user 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
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" ) )
200 port = getPortFromORBcfg()
201 if port is not None: return port
202 if use_default: return 2809 # '2809' is default port number
209 Get directory to be used for the temporary files.
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")
217 # for Linux: use /tmp/logs/{user} folder
218 dir = os.path.join( '/tmp', 'logs', getUserName() )
224 def generateFileName( dir, prefix = None, suffix = None, extension = None,
225 unique = False, separator = "_", hidden = False, **kwargs ):
227 Generate file name by sepecified parameters. If necessary, file name
228 can be generated to be unique.
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.
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.
258 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
259 from launchConfigureParser import verbose
262 if separator is None:
266 separator = str( separator )
268 # prefix (if specified)
269 if prefix is not None:
270 filename.append( str( prefix ) )
272 # additional keywords
273 ### check unsupported parameters
275 if kw not in supported and verbose():
276 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
279 ### process supported keywords
281 if kw not in kwargs: continue
283 if kw == 'with_username':
286 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
289 # user name given as parameter
290 filename.append( kwargs[kw] )
294 elif kw == 'with_hostname':
297 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
300 # host name given as parameter
301 filename.append( kwargs[kw] )
305 elif kw == 'with_port':
308 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
311 # port number given as parameter
312 filename.append( str( kwargs[kw] ) )
316 elif kw == 'with_app':
318 # auto application name ?
319 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
322 # application name given as parameter
323 filename.append( kwargs[kw] )
327 # suffix (if specified)
328 if suffix is not None:
329 filename.append( str( suffix ) )
331 # raise an exception if file name is empty
333 raise Exception("Empty file name")
335 if extension is not None and extension.startswith("."): extension = extension[1:]
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 )
343 # create unique file name
345 while os.path.exists( name ):
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 )
353 return os.path.normpath(name)
357 def makeTmpDir( path, mode=0777 ):
359 Make temporary directory with the specified path.
360 If the directory exists then clear its contents.
363 - path : absolute path to the directory to be created.
367 if os.path.exists( path ):
369 if sys.platform == "win32":
370 os.system( "rmdir /S /Q " + '"' + path + '"' )
371 os.system( "mkdir " + '"' + path + '"' )
373 os.system( "rm -rf " + path + "/*" )
377 dirs = path.split("/")
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])
394 def uniteFiles( src_file, dest_file ):
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
402 - src_file : absolute path to the source file
403 - dest_file : absolute path to the destination file
407 if not os.path.exists( src_file ):
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()
417 dest_lines.append( "\n" )
419 dest = open( dest_file, 'w' )
420 dest.writelines( dest_lines )
424 if sys.platform == "win32":
425 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
427 command = "cat " + src_file + " >> " + dest_file
432 if sys.platform == "win32":
433 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
435 command = "cp " + src_file + " " + dest_file