1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
4 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License.
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 # File : salome_utils.py
25 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
28 ## @package salome_utils
29 # \brief Set of utility functions used by SALOME python scripts.
55 Check if specified parameter represents boolean value and returns its value.
56 String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
58 If <arg> does not represent a boolean, an exception is raised.
61 if type( arg ) == types.BooleanType :
63 elif type( arg ) == types.StringType :
64 v = str( arg ).lower()
65 if v in [ "yes", "y", "true" ]: return True
66 elif v in [ "no", "n", "false" ]: return False
68 raise Exception("Not boolean value")
74 Get omniORB current configuration.
75 Returns a list of three values: [ orb_version, host_name, port_number ].
77 The information is retrieved from the omniORB configuration file defined
78 by the OMNIORB_CONFIG environment variable.
79 If omniORB configuration file can not be accessed, a list of three empty
85 f = open( os.getenv( "OMNIORB_CONFIG" ) )
88 regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
93 if m.group(1) is None:
112 def getHostFromORBcfg():
114 Get current omniORB host.
116 return getORBcfgInfo()[1]
119 def getPortFromORBcfg():
121 Get current omniORB port.
123 return getORBcfgInfo()[2]
130 1. try USER environment variable
131 2. if fails, return 'unknown' as default user name
134 return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
141 1. try socket python module gethostname() function
142 2. if fails, try HOSTNAME environment variable
143 3. if fails, try HOST environment variable
144 4. if fails, return 'unknown' as default host name
149 host = socket.gethostname()
153 if not host: host = os.getenv("HOSTNAME")
154 if not host: host = os.getenv("HOST")
155 if not host: host = "unknown" # 'unknown' is default host name
160 def getShortHostName():
163 1. try socket python module gethostname() function
164 2. if fails, try HOSTNAME environment variable
165 3. if fails, try HOST environment variable
166 4. if fails, return 'unknown' as default host name
169 return getHostName().split('.')[0]
172 return "unknown" # 'unknown' is default host name
178 Get application name:
179 1. try APPNAME environment variable
180 2. if fails, return 'SALOME' as default application name
183 return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
187 def getPortNumber(use_default=True):
189 Get current naming server port number:
190 1. try NSPORT environment variable
191 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
192 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
196 return int( os.getenv( "NSPORT" ) )
199 port = getPortFromORBcfg()
200 if port is not None: return port
201 if use_default: return 2809 # '2809' is default port number
208 Get directory to be used for the temporary files.
211 if sys.platform == "win32":
212 # for Windows: temporarily using home directory for tmp files;
213 # to be replaced with TEMP environment variable later...
214 dir = os.getenv("HOME")
216 # for Linux: use /tmp/logs/{user} folder
217 dir = os.path.join( '/tmp', 'logs', getUserName() )
223 def generateFileName( dir, prefix = None, suffix = None, extension = None,
224 unique = False, separator = "_", hidden = False, **kwargs ):
226 Generate file name by sepecified parameters. If necessary, file name
227 can be generated to be unique.
230 - dir : directory path
231 - prefix : file prefix (not added by default)
232 - suffix : file suffix (not added by default)
233 - extension : file extension (not added by default)
234 - unique : if this parameter is True, the unique file name is generated:
235 in this case, if the file with the generated name already exists
236 in the <dir> directory, an integer suffix is added to the end of the
237 file name. This parameter is False by default.
238 - separator : separator of the words ('_' by default)
239 - hidden : if this parameter is True, the file name is prepended by . (dot)
240 symbol. This parameter is False by default.
242 Other keyword parameters are:
243 - with_username : 'add user name' flag/option:
244 * boolean value can be passed to determine user name automatically
245 * string value to be used as user name
246 - with_hostname : 'add host name' flag/option:
247 * boolean value can be passed to determine host name automatically
248 * string value to be used as host name
249 - with_port : 'add port number' flag/option:
250 * boolean value can be passed to determine port number automatically
251 * string value to be used as port number
252 - with_app : 'add application name' flag/option:
253 * boolean value can be passed to determine application name automatically
254 * string value to be used as application name
255 All <with_...> parameters are optional.
257 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
258 from launchConfigureParser import verbose
261 if separator is None:
265 separator = str( separator )
267 # prefix (if specified)
268 if prefix is not None:
269 filename.append( str( prefix ) )
271 # additional keywords
272 ### check unsupported parameters
274 if kw not in supported and verbose():
275 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
278 ### process supported keywords
280 if kw not in kwargs: continue
282 if kw == 'with_username':
285 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
288 # user name given as parameter
289 filename.append( kwargs[kw] )
293 elif kw == 'with_hostname':
296 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
299 # host name given as parameter
300 filename.append( kwargs[kw] )
304 elif kw == 'with_port':
307 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
310 # port number given as parameter
311 filename.append( str( kwargs[kw] ) )
315 elif kw == 'with_app':
317 # auto application name ?
318 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
321 # application name given as parameter
322 filename.append( kwargs[kw] )
326 # suffix (if specified)
327 if suffix is not None:
328 filename.append( str( suffix ) )
330 # raise an exception if file name is empty
332 raise Exception("Empty file name")
334 if extension is not None and extension.startswith("."): extension = extension[1:]
337 name = separator.join( filename )
338 if hidden: name = "." + name # add dot for hidden files
339 if extension: name = name + "." + str( extension ) # add extension if defined
340 name = os.path.join( dir, name )
342 # create unique file name
344 while os.path.exists( name ):
346 name = separator.join( filename ) + separator + str( index )
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 )
352 return os.path.normpath(name)
356 def makeTmpDir( path, mode=0777 ):
358 Make temporary directory with the specified path.
359 If the directory exists then clear its contents.
362 - path : absolute path to the directory to be created.
366 if os.path.exists( path ):
368 if sys.platform == "win32":
369 os.system( "rmdir /S /Q " + '"' + path + '"' )
370 os.system( "mkdir " + '"' + path + '"' )
372 os.system( "rm -rf " + path + "/*" )
376 dirs = path.split("/")
378 if not dirs[0]: shift1 = 1
379 if dirs[-1]: shift2 = 1
380 for i in range(1+shift1,len(dirs)+shift2):
381 p = "/".join(dirs[:i])
393 def uniteFiles( src_file, dest_file ):
395 Unite contents of the source file with contents of the destination file
396 and put result of the uniting to the destination file.
397 If the destination file does not exist then the source file is simply
401 - src_file : absolute path to the source file
402 - dest_file : absolute path to the destination file
406 if not os.path.exists( src_file ):
410 if os.path.exists( dest_file ):
411 # add a symbol of new line to contents of the destination file (just in case)
412 dest = open( dest_file, 'r' )
413 dest_lines = dest.readlines()
416 dest_lines.append( "\n" )
418 dest = open( dest_file, 'w' )
419 dest.writelines( dest_lines )
423 if sys.platform == "win32":
424 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
426 command = "cat " + src_file + " >> " + dest_file
431 if sys.platform == "win32":
432 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
434 command = "cp " + src_file + " " + dest_file