1 # Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
3 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License.
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 # File : salome_utils.py
24 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
27 ## @package salome_utils
28 # \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
130 2. if fails, return 'unknown' as default user name
133 return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
140 1. try socket python module gethostname() function
141 2. if fails, try HOSTNAME environment variable
142 3. if fails, try HOST environment variable
143 4. if fails, return 'unknown' as default host name
148 host = socket.gethostname()
152 if not host: host = os.getenv("HOSTNAME")
153 if not host: host = os.getenv("HOST")
154 if not host: host = "unknown" # 'unknown' is default host name
159 def getShortHostName():
162 1. try socket python module gethostname() function
163 2. if fails, try HOSTNAME environment variable
164 3. if fails, try HOST environment variable
165 4. if fails, return 'unknown' as default host name
168 return getHostName().split('.')[0]
171 return "unknown" # 'unknown' is default host name
177 Get application name:
178 1. try APPNAME environment variable
179 2. if fails, return 'SALOME' as default application name
182 return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
186 def getPortNumber(use_default=True):
188 Get current naming server port number:
189 1. try NSPORT environment variable
190 1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
191 2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
195 return int( os.getenv( "NSPORT" ) )
198 port = getPortFromORBcfg()
199 if port is not None: return port
200 if use_default: return 2809 # '2809' is default port number
207 Get directory to be used for the temporary files.
210 if sys.platform == "win32":
211 # for Windows: temporarily using home directory for tmp files;
212 # to be replaced with TEMP environment variable later...
213 dir = os.getenv("HOME")
215 # for Linux: use /tmp/logs/{user} folder
216 dir = os.path.join( '/tmp', 'logs', getUserName() )
222 def generateFileName( dir, prefix = None, suffix = None, extension = None,
223 unique = False, separator = "_", hidden = False, **kwargs ):
225 Generate file name by sepecified parameters. If necessary, file name
226 can be generated to be unique.
229 - dir : directory path
230 - prefix : file prefix (not added by default)
231 - suffix : file suffix (not added by default)
232 - extension : file extension (not added by default)
233 - unique : if this parameter is True, the unique file name is generated:
234 in this case, if the file with the generated name already exists
235 in the <dir> directory, an integer suffix is added to the end of the
236 file name. This parameter is False by default.
237 - separator : separator of the words ('_' by default)
238 - hidden : if this parameter is True, the file name is prepended by . (dot)
239 symbol. This parameter is False by default.
241 Other keyword parameters are:
242 - with_username : 'add user name' flag/option:
243 * boolean value can be passed to determine user name automatically
244 * string value to be used as user name
245 - with_hostname : 'add host name' flag/option:
246 * boolean value can be passed to determine host name automatically
247 * string value to be used as host name
248 - with_port : 'add port number' flag/option:
249 * boolean value can be passed to determine port number automatically
250 * string value to be used as port number
251 - with_app : 'add application name' flag/option:
252 * boolean value can be passed to determine application name automatically
253 * string value to be used as application name
254 All <with_...> parameters are optional.
256 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
257 from launchConfigureParser import verbose
260 if separator is None:
264 separator = str( separator )
266 # prefix (if specified)
267 if prefix is not None:
268 filename.append( str( prefix ) )
270 # additional keywords
271 ### check unsupported parameters
273 if kw not in supported and verbose():
274 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
277 ### process supported keywords
279 if kw not in kwargs: continue
281 if kw == 'with_username':
284 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
287 # user name given as parameter
288 filename.append( kwargs[kw] )
292 elif kw == 'with_hostname':
295 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
298 # host name given as parameter
299 filename.append( kwargs[kw] )
303 elif kw == 'with_port':
306 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
309 # port number given as parameter
310 filename.append( str( kwargs[kw] ) )
314 elif kw == 'with_app':
316 # auto application name ?
317 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
320 # application name given as parameter
321 filename.append( kwargs[kw] )
325 # suffix (if specified)
326 if suffix is not None:
327 filename.append( str( suffix ) )
329 # raise an exception if file name is empty
331 raise Exception("Empty file name")
333 if extension is not None and extension.startswith("."): extension = extension[1:]
336 name = separator.join( filename )
337 if hidden: name = "." + name # add dot for hidden files
338 if extension: name = name + "." + str( extension ) # add extension if defined
339 name = os.path.join( dir, name )
341 # create unique file name
343 while os.path.exists( name ):
345 name = separator.join( filename ) + separator + str( index )
346 if hidden: name = "." + name # add dot for hidden files
347 if extension: name = name + "." + str( extension ) # add extension if defined
348 name = os.path.join( dir, name )
351 return os.path.normpath(name)
355 def makeTmpDir( path, mode=0777 ):
357 Make temporary directory with the specified path.
358 If the directory exists then clear its contents.
361 - path : absolute path to the directory to be created.
365 if os.path.exists( path ):
367 if sys.platform == "win32":
368 os.system( "rmdir /S /Q " + '"' + path + '"' )
369 os.system( "mkdir " + '"' + path + '"' )
371 os.system( "rm -rf " + path + "/*" )
375 dirs = path.split("/")
377 if not dirs[0]: shift1 = 1
378 if dirs[-1]: shift2 = 1
379 for i in range(1+shift1,len(dirs)+shift2):
380 p = "/".join(dirs[:i])
392 def uniteFiles( src_file, dest_file ):
394 Unite contents of the source file with contents of the destination file
395 and put result of the uniting to the destination file.
396 If the destination file does not exist then the source file is simply
400 - src_file : absolute path to the source file
401 - dest_file : absolute path to the destination file
405 if not os.path.exists( src_file ):
409 if os.path.exists( dest_file ):
410 # add a symbol of new line to contents of the destination file (just in case)
411 dest = open( dest_file, 'r' )
412 dest_lines = dest.readlines()
415 dest_lines.append( "\n" )
417 dest = open( dest_file, 'w' )
418 dest.writelines( dest_lines )
422 if sys.platform == "win32":
423 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
425 command = "cat " + src_file + " >> " + dest_file
430 if sys.platform == "win32":
431 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
433 command = "cp " + src_file + " " + dest_file