Back to index

salome-kernel  6.5.0
Functions | Variables
salome_utils Namespace Reference

Set of utility functions used by SALOME python scripts. More...

Functions

def _try_bool
def getORBcfgInfo
def getHostFromORBcfg
def getPortFromORBcfg
def getUserName
def getHostName
def getShortHostName
def getAppName
def getPortNumber
def getHomeDir
def getTmpDir
def generateFileName
def makeTmpDir
def uniteFiles
def verbose
def setVerbose

Variables

list __all__
 _verbose = None

Detailed Description

Set of utility functions used by SALOME python scripts.


Function Documentation

def salome_utils._try_bool (   arg) [private]
Check if specified parameter represents boolean value and returns its value.
String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
are supported.
If <arg> does not represent a boolean, an exception is raised.

Definition at line 51 of file salome_utils.py.

00051 
00052 def _try_bool( arg ):
00053     """
00054     Check if specified parameter represents boolean value and returns its value.
00055     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
00056     are supported.
00057     If <arg> does not represent a boolean, an exception is raised.
00058     """
00059     import types
00060     if type( arg ) == types.BooleanType  :
00061         return arg
00062     elif type( arg ) == types.StringType  :
00063         v = str( arg ).lower()
00064         if   v in [ "yes", "y", "true"  ]: return True
00065         elif v in [ "no",  "n", "false" ]: return False
00066         pass
00067     raise Exception("Not boolean value")
00068 
00069 # ---

Here is the caller graph for this function:

def salome_utils.generateFileName (   dir,
  prefix = None,
  suffix = None,
  extension = None,
  unique = False,
  separator = "_",
  hidden = False,
  kwargs 
)
Generate file name by sepecified parameters. If necessary, file name
can be generated to be unique.

Parameters:
- dir       : directory path
- prefix    : file prefix (not added by default)
- suffix    : file suffix (not added by default)
- extension : file extension (not added by default)
- unique    : if this parameter is True, the unique file name is generated:
in this case, if the file with the generated name already exists
in the <dir> directory, an integer suffix is added to the end of the
file name. This parameter is False by default.
- separator : separator of the words ('_' by default)
- hidden    : if this parameter is True, the file name is prepended by . (dot)
symbol. This parameter is False by default.

Other keyword parameters are:
- with_username : 'add user name' flag/option:
  * boolean value can be passed to determine user name automatically
  * string value to be used as user name
- with_hostname : 'add host name' flag/option:
  * boolean value can be passed to determine host name automatically
  * string value to be used as host name
- with_port     : 'add port number' flag/option:
  * boolean value can be passed to determine port number automatically
  * string value to be used as port number
- with_app      : 'add application name' flag/option:
  * boolean value can be passed to determine application name automatically
  * string value to be used as application name
All <with_...> parameters are optional.

Definition at line 246 of file salome_utils.py.

00246 
00247                       unique = False, separator = "_", hidden = False, **kwargs ):
00248     """
00249     Generate file name by sepecified parameters. If necessary, file name
00250     can be generated to be unique.
00251 
00252     Parameters:
00253     - dir       : directory path
00254     - prefix    : file prefix (not added by default)
00255     - suffix    : file suffix (not added by default)
00256     - extension : file extension (not added by default)
00257     - unique    : if this parameter is True, the unique file name is generated:
00258     in this case, if the file with the generated name already exists
00259     in the <dir> directory, an integer suffix is added to the end of the
00260     file name. This parameter is False by default.
00261     - separator : separator of the words ('_' by default)
00262     - hidden    : if this parameter is True, the file name is prepended by . (dot)
00263     symbol. This parameter is False by default.
00264 
00265     Other keyword parameters are:
00266     - with_username : 'add user name' flag/option:
00267       * boolean value can be passed to determine user name automatically
00268       * string value to be used as user name
00269     - with_hostname : 'add host name' flag/option:
00270       * boolean value can be passed to determine host name automatically
00271       * string value to be used as host name
00272     - with_port     : 'add port number' flag/option:
00273       * boolean value can be passed to determine port number automatically
00274       * string value to be used as port number
00275     - with_app      : 'add application name' flag/option:
00276       * boolean value can be passed to determine application name automatically
00277       * string value to be used as application name
00278     All <with_...> parameters are optional.
00279     """
00280     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
00281     from launchConfigureParser import verbose
00282     filename = []
00283     # separator
00284     if separator is None:
00285         separator = ""
00286         pass
00287     else:
00288         separator = str( separator )
00289         pass
00290     # prefix (if specified)
00291     if prefix is not None:
00292         filename.append( str( prefix ) )
00293         pass
00294     # additional keywords
00295     ### check unsupported parameters
00296     for kw in kwargs:
00297         if kw not in supported and verbose():
00298             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
00299             pass
00300         pass
00301     ### process supported keywords
00302     for kw in supported:
00303         if kw not in kwargs: continue
00304         ### user name
00305         if kw == 'with_username':
00306             try:
00307                 # auto user name ?
00308                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
00309                 pass
00310             except:
00311                 # user name given as parameter
00312                 filename.append( kwargs[kw] )
00313                 pass
00314             pass
00315         ### host name
00316         elif kw == 'with_hostname':
00317             try:
00318                 # auto host name ?
00319                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
00320                 pass
00321             except:
00322                 # host name given as parameter
00323                 filename.append( kwargs[kw] )
00324                 pass
00325             pass
00326         ### port number
00327         elif kw == 'with_port':
00328             try:
00329                 # auto port number ?
00330                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
00331                 pass
00332             except:
00333                 # port number given as parameter
00334                 filename.append( str( kwargs[kw] ) )
00335                 pass
00336             pass
00337         ### application name
00338         elif kw == 'with_app':
00339             try:
00340                 # auto application name ?
00341                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
00342                 pass
00343             except:
00344                 # application name given as parameter
00345                 filename.append( kwargs[kw] )
00346                 pass
00347             pass
00348         pass
00349     # suffix (if specified)
00350     if suffix is not None:
00351         filename.append( str( suffix ) )
00352         pass
00353     # raise an exception if file name is empty
00354     if not filename:
00355         raise Exception("Empty file name")
00356     #
00357     if extension is not None and extension.startswith("."): extension = extension[1:]
00358     #
00359     import os
00360     name = separator.join( filename )
00361     if hidden: name = "." + name                       # add dot for hidden files
00362     if extension: name = name + "." + str( extension ) # add extension if defined
00363     name = os.path.join( dir, name )
00364     if unique:
00365         # create unique file name
00366         index = 0
00367         while os.path.exists( name ):
00368             index = index + 1
00369             name = separator.join( filename ) + separator + str( index )
00370             if hidden: name = "." + name                       # add dot for hidden files
00371             if extension: name = name + "." + str( extension ) # add extension if defined
00372             name = os.path.join( dir, name )
00373             pass
00374         pass
00375     return os.path.normpath(name)
00376 
00377 # ---

Here is the call graph for this function:

Here is the caller graph for this function:

Get application name:
1. try APPNAME environment variable
2. if fails, return 'SALOME' as default application name

Definition at line 174 of file salome_utils.py.

00174 
00175 def getAppName():
00176     """
00177     Get application name:
00178     1. try APPNAME environment variable
00179     2. if fails, return 'SALOME' as default application name
00180     """
00181     import os
00182     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
00183 
00184 # ---

Here is the caller graph for this function:

Get home directory.

Definition at line 204 of file salome_utils.py.

00204 
00205 def getHomeDir():
00206     """
00207     Get home directory.
00208     """
00209     import os, sys
00210     if sys.platform == "win32":
00211         # for Windows the home directory is detected in the following way:
00212         # 1. try USERPROFILE env variable
00213         # 2. try combination of HOMEDRIVE and HOMEPATH env variables
00214         # 3. try HOME env variable
00215         # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used
00216         dir = os.getenv("USERPROFILE")
00217         if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
00218             dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
00219         if not dir:
00220             dir = os.getenv("HOME")
00221         pass
00222     else:
00223         # for Linux: use HOME variable
00224         dir = os.getenv("HOME")
00225         pass
00226     return dir
00227 # ---

Here is the caller graph for this function:

Get current omniORB host.

Definition at line 110 of file salome_utils.py.

00110 
00111 def getHostFromORBcfg():
00112     """
00113     Get current omniORB host.
00114     """
00115     return getORBcfgInfo()[1]
00116 # ---

Here is the call graph for this function:

Get host name:
1. try socket python module gethostname() function
2. if fails, try HOSTNAME environment variable
3. if fails, try HOST environment variable
4. if fails, return 'unknown' as default host name

Definition at line 136 of file salome_utils.py.

00136 
00137 def getHostName():
00138     """
00139     Get host name:
00140     1. try socket python module gethostname() function
00141     2. if fails, try HOSTNAME environment variable
00142     3. if fails, try HOST environment variable
00143     4. if fails, return 'unknown' as default host name
00144     """
00145     import os
00146     try:
00147         import socket
00148         host = socket.gethostname()
00149     except:
00150         host = None
00151         pass
00152     if not host: host = os.getenv("HOSTNAME")
00153     if not host: host = os.getenv("HOST")
00154     if not host: host = "unknown"           # 'unknown' is default host name
00155     return host
00156 
00157 # ---

Here is the caller graph for this function:

Get omniORB current configuration.
Returns a list of three values: [ orb_version, host_name, port_number ].

The information is retrieved from the omniORB configuration file defined
by the OMNIORB_CONFIG environment variable.
If omniORB configuration file can not be accessed, a list of three empty
strings is returned.

Definition at line 70 of file salome_utils.py.

00070 
00071 def getORBcfgInfo():
00072     """
00073     Get omniORB current configuration.
00074     Returns a list of three values: [ orb_version, host_name, port_number ].
00075     
00076     The information is retrieved from the omniORB configuration file defined
00077     by the OMNIORB_CONFIG environment variable.
00078     If omniORB configuration file can not be accessed, a list of three empty
00079     strings is returned.
00080     """
00081     import os, re
00082     ret = [ "", "", "" ]
00083     try:
00084         f = open( os.getenv( "OMNIORB_CONFIG" ) )
00085         lines = f.readlines()
00086         f.close()
00087         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
00088         for l in lines:
00089             try:
00090                 m = regvar.match( l )
00091                 if m:
00092                     if m.group(1) is None:
00093                         ret[0] = "4"
00094                     else:
00095                         ret[0] = "3"
00096                         pass
00097                     ret[1] = m.group(2)
00098                     ret[2] = m.group(3)
00099                     break
00100                 pass
00101             except:
00102                 pass
00103             pass
00104         pass
00105     except:
00106         pass
00107     return ret
00108 
00109 # ---

Here is the caller graph for this function:

Get current omniORB port.

Definition at line 117 of file salome_utils.py.

00117 
00118 def getPortFromORBcfg():
00119     """
00120     Get current omniORB port.
00121     """
00122     return getORBcfgInfo()[2]
00123 
00124 # ---

Here is the call graph for this function:

Here is the caller graph for this function:

def salome_utils.getPortNumber (   use_default = True)
Get current naming server port number:
1. try NSPORT environment variable
1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)

Definition at line 185 of file salome_utils.py.

00185 
00186 def getPortNumber(use_default=True):
00187     """
00188     Get current naming server port number:
00189     1. try NSPORT environment variable
00190     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
00191     2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
00192     """
00193     import os
00194     try:
00195         return int( os.getenv( "NSPORT" ) )
00196     except:
00197         pass
00198     port = getPortFromORBcfg()
00199     if port is not None: return port
00200     if use_default: return 2809 # '2809' is default port number
00201     return None
00202 
00203 # ---

Here is the call graph for this function:

Here is the caller graph for this function:

Get short host name:
1. try socket python module gethostname() function
2. if fails, try HOSTNAME environment variable
3. if fails, try HOST environment variable
4. if fails, return 'unknown' as default host name

Definition at line 158 of file salome_utils.py.

00158 
00159 def getShortHostName():
00160     """
00161     Get short host name:
00162     1. try socket python module gethostname() function
00163     2. if fails, try HOSTNAME environment variable
00164     3. if fails, try HOST environment variable
00165     4. if fails, return 'unknown' as default host name
00166     """
00167     try:
00168         return getHostName().split('.')[0]
00169     except:
00170         pass
00171     return "unknown"           # 'unknown' is default host name
00172     
00173 # ---

Here is the call graph for this function:

Here is the caller graph for this function:

Get directory to be used for the temporary files.

Definition at line 228 of file salome_utils.py.

00228 
00229 def getTmpDir():
00230     """
00231     Get directory to be used for the temporary files.
00232     """
00233     import os, sys
00234     if sys.platform == "win32":
00235         # for Windows: temporarily using home directory for tmp files;
00236         # to be replaced with TEMP environment variable later...
00237         dir = os.getenv("HOME")
00238     else:
00239         # for Linux: use /tmp/logs/{user} folder
00240         dir = os.path.join( '/tmp', 'logs', getUserName() )
00241         pass
00242     return dir
00243 
00244 # ---

Here is the call graph for this function:

Here is the caller graph for this function:

Get user name:
1. try USER environment variable
2. if fails, return 'unknown' as default user name

Definition at line 125 of file salome_utils.py.

00125 
00126 def getUserName():
00127     """
00128     Get user name:
00129     1. try USER environment variable
00130     2. if fails, return 'unknown' as default user name
00131     """
00132     import os
00133     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
00134 
00135 # ---

Here is the caller graph for this function:

def salome_utils.makeTmpDir (   path,
  mode = 0777 
)
Make temporary directory with the specified path.
If the directory exists then clear its contents.

Parameters:
- path : absolute path to the directory to be created.
- mode : access mode

Definition at line 378 of file salome_utils.py.

00378 
00379 def makeTmpDir( path, mode=0777 ):
00380     """
00381     Make temporary directory with the specified path.
00382     If the directory exists then clear its contents.
00383 
00384     Parameters:
00385     - path : absolute path to the directory to be created.
00386     - mode : access mode
00387     """
00388     import os
00389     if os.path.exists( path ):
00390         import sys
00391         if sys.platform == "win32":
00392             os.system( "rmdir /S /Q " + '"' + path + '"' )
00393             os.system( "mkdir " + '"' + path + '"' )
00394         else:
00395             os.system( "rm -rf " + path + "/*" )
00396     else:
00397         dirs = path.split("/")
00398         shift1 = shift2 = 0
00399         if not dirs[0]: shift1 = 1
00400         if dirs[-1]: shift2 = 1
00401         for i in range(1+shift1,len(dirs)+shift2):
00402             p = "/".join(dirs[:i])
00403             try:
00404                 os.mkdir(p, mode)
00405                 os.chmod(p, mode)
00406             except:
00407                 pass
00408 
00409 # ---

Here is the caller graph for this function:

def salome_utils.setVerbose (   level)
Change verbosity level. The function verbose() can be used to get current verbosity level.

Definition at line 482 of file salome_utils.py.

00482 
00483 def setVerbose(level):
00484     """
00485     Change verbosity level. The function verbose() can be used to get current verbosity level.
00486     """
00487     global _verbose
00488     _verbose = level
00489     return
00490 
def salome_utils.uniteFiles (   src_file,
  dest_file 
)
Unite contents of the source file with contents of the destination file
and put result of the uniting to the destination file.
If the destination file does not exist then the source file is simply
copied to its path.

Parameters:
- src_file  : absolute path to the source file
- dest_file : absolute path to the destination file

Definition at line 410 of file salome_utils.py.

00410 
00411 def uniteFiles( src_file, dest_file ):
00412     """
00413     Unite contents of the source file with contents of the destination file
00414     and put result of the uniting to the destination file.
00415     If the destination file does not exist then the source file is simply
00416     copied to its path.
00417 
00418     Parameters:
00419     - src_file  : absolute path to the source file
00420     - dest_file : absolute path to the destination file
00421     """
00422     import os
00423 
00424     if not os.path.exists( src_file ):
00425         return
00426         pass
00427 
00428     if os.path.exists( dest_file ):
00429         # add a symbol of new line to contents of the destination file (just in case)
00430         dest = open( dest_file, 'r' )
00431         dest_lines = dest.readlines()
00432         dest.close()
00433 
00434         dest_lines.append( "\n" )
00435 
00436         dest = open( dest_file, 'w' )
00437         dest.writelines( dest_lines )
00438         dest.close()
00439 
00440         import sys
00441         if sys.platform == "win32":
00442             command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
00443         else:
00444             command = "cat " + src_file + " >> " + dest_file
00445             pass
00446         pass
00447     else:
00448         import sys
00449         if sys.platform == "win32":
00450             command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
00451         else:
00452             command = "cp " + src_file + " " + dest_file
00453             pass
00454         pass
00455 
00456     os.system( command )
00457 
00458 # --

Get verbosity level. Default verbosity level is specified via the environment variable
SALOME_VERBOSE, e.g.:
[bash %] export SALOME_VERBOSE=1
The function setVerbose() can be used to change verbosity level explicitly.

Definition at line 461 of file salome_utils.py.

00461 
00462 def verbose():
00463     """
00464     Get verbosity level. Default verbosity level is specified via the environment variable
00465     SALOME_VERBOSE, e.g.:
00466     [bash %] export SALOME_VERBOSE=1
00467     The function setVerbose() can be used to change verbosity level explicitly.
00468     """
00469     global _verbose
00470     # verbose has already been called
00471     if _verbose is not None:
00472         return _verbose
00473     # first time
00474     try:
00475         from os import getenv
00476         _verbose = int(getenv('SALOME_VERBOSE'))
00477     except:
00478         _verbose = 0
00479         pass
00480     #
00481     return _verbose

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 [
00002     'getORBcfgInfo',
00003     'getHostFromORBcfg',
00004     'getPortFromORBcfg',
00005     'getUserName',
00006     'getHostName',
00007     'getShortHostName',
00008     'getAppName',
00009     'getPortNumber',
00010     'getTmpDir',
00011     'getHomeDir',
00012     'generateFileName',
00013     'makeTmpDir',
00014     'uniteFiles',
00015     ]

Definition at line 33 of file salome_utils.py.

Definition at line 459 of file salome_utils.py.