1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2012 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" ) )
197 port = getPortFromORBcfg()
198 if port is not None: return port
199 if use_default: return 2809 # '2809' is default port number
209 if sys.platform == "win32":
210 # for Windows the home directory is detected in the following way:
211 # 1. try USERPROFILE env variable
212 # 2. try combination of HOMEDRIVE and HOMEPATH env variables
213 # 3. try HOME env variable
214 # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used
215 dir = os.getenv("USERPROFILE")
216 if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
217 dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
219 dir = os.getenv("HOME")
222 # for Linux: use HOME variable
223 dir = os.getenv("HOME")
230 Get directory to be used for the temporary files.
233 if sys.platform == "win32":
234 # for Windows: temporarily using home directory for tmp files;
235 # to be replaced with TEMP environment variable later...
236 dir = os.getenv("HOME")
238 # for Linux: use /tmp/logs/{user} folder
239 dir = os.path.join( '/tmp', 'logs', getUserName() )
245 def generateFileName( dir, prefix = None, suffix = None, extension = None,
246 unique = False, separator = "_", hidden = False, **kwargs ):
248 Generate file name by sepecified parameters. If necessary, file name
249 can be generated to be unique.
252 - dir : directory path
253 - prefix : file prefix (not added by default)
254 - suffix : file suffix (not added by default)
255 - extension : file extension (not added by default)
256 - unique : if this parameter is True, the unique file name is generated:
257 in this case, if the file with the generated name already exists
258 in the <dir> directory, an integer suffix is added to the end of the
259 file name. This parameter is False by default.
260 - separator : separator of the words ('_' by default)
261 - hidden : if this parameter is True, the file name is prepended by . (dot)
262 symbol. This parameter is False by default.
264 Other keyword parameters are:
265 - with_username : 'add user name' flag/option:
266 * boolean value can be passed to determine user name automatically
267 * string value to be used as user name
268 - with_hostname : 'add host name' flag/option:
269 * boolean value can be passed to determine host name automatically
270 * string value to be used as host name
271 - with_port : 'add port number' flag/option:
272 * boolean value can be passed to determine port number automatically
273 * string value to be used as port number
274 - with_app : 'add application name' flag/option:
275 * boolean value can be passed to determine application name automatically
276 * string value to be used as application name
277 All <with_...> parameters are optional.
279 supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
280 from launchConfigureParser import verbose
283 if separator is None:
287 separator = str( separator )
289 # prefix (if specified)
290 if prefix is not None:
291 filename.append( str( prefix ) )
293 # additional keywords
294 ### check unsupported parameters
296 if kw not in supported and verbose():
297 print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
300 ### process supported keywords
302 if kw not in kwargs: continue
304 if kw == 'with_username':
307 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
310 # user name given as parameter
311 filename.append( kwargs[kw] )
315 elif kw == 'with_hostname':
318 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
321 # host name given as parameter
322 filename.append( kwargs[kw] )
326 elif kw == 'with_port':
329 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
332 # port number given as parameter
333 filename.append( str( kwargs[kw] ) )
337 elif kw == 'with_app':
339 # auto application name ?
340 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
343 # application name given as parameter
344 filename.append( kwargs[kw] )
348 # suffix (if specified)
349 if suffix is not None:
350 filename.append( str( suffix ) )
352 # raise an exception if file name is empty
354 raise Exception("Empty file name")
356 if extension is not None and extension.startswith("."): extension = extension[1:]
359 name = separator.join( filename )
360 if hidden: name = "." + name # add dot for hidden files
361 if extension: name = name + "." + str( extension ) # add extension if defined
362 name = os.path.join( dir, name )
364 # create unique file name
366 while os.path.exists( name ):
368 name = separator.join( filename ) + separator + str( index )
369 if hidden: name = "." + name # add dot for hidden files
370 if extension: name = name + "." + str( extension ) # add extension if defined
371 name = os.path.join( dir, name )
374 return os.path.normpath(name)
378 def makeTmpDir( path, mode=0777 ):
380 Make temporary directory with the specified path.
381 If the directory exists then clear its contents.
384 - path : absolute path to the directory to be created.
388 if os.path.exists( path ):
390 if sys.platform == "win32":
391 os.system( "rmdir /S /Q " + '"' + path + '"' )
392 os.system( "mkdir " + '"' + path + '"' )
394 os.system( "rm -rf " + path + "/*" )
396 dirs = path.split("/")
398 if not dirs[0]: shift1 = 1
399 if dirs[-1]: shift2 = 1
400 for i in range(1+shift1,len(dirs)+shift2):
401 p = "/".join(dirs[:i])
410 def uniteFiles( src_file, dest_file ):
412 Unite contents of the source file with contents of the destination file
413 and put result of the uniting to the destination file.
414 If the destination file does not exist then the source file is simply
418 - src_file : absolute path to the source file
419 - dest_file : absolute path to the destination file
423 if not os.path.exists( src_file ):
427 if os.path.exists( dest_file ):
428 # add a symbol of new line to contents of the destination file (just in case)
429 dest = open( dest_file, 'r' )
430 dest_lines = dest.readlines()
433 dest_lines.append( "\n" )
435 dest = open( dest_file, 'w' )
436 dest.writelines( dest_lines )
440 if sys.platform == "win32":
441 command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
443 command = "cat " + src_file + " >> " + dest_file
448 if sys.platform == "win32":
449 command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
451 command = "cp " + src_file + " " + dest_file
463 Get verbosity level. Default verbosity level is specified via the environment variable
464 SALOME_VERBOSE, e.g.:
465 [bash %] export SALOME_VERBOSE=1
466 The function setVerbose() can be used to change verbosity level explicitly.
469 # verbose has already been called
470 if _verbose is not None:
474 from os import getenv
475 _verbose = int(getenv('SALOME_VERBOSE'))
482 def setVerbose(level):
484 Change verbosity level. The function verbose() can be used to get current verbosity level.