Back to index

salome-kernel  6.5.0
salome_utils.py
Go to the documentation of this file.
00001 #  -*- coding: iso-8859-1 -*-
00002 # Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00003 #
00004 # This library is free software; you can redistribute it and/or
00005 # modify it under the terms of the GNU Lesser General Public
00006 # License as published by the Free Software Foundation; either
00007 # version 2.1 of the License.
00008 #
00009 # This library is distributed in the hope that it will be useful,
00010 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012 # Lesser General Public License for more details.
00013 #
00014 # You should have received a copy of the GNU Lesser General Public
00015 # License along with this library; if not, write to the Free Software
00016 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00017 #
00018 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00019 #
00020 
00021 # ---
00022 # File   : salome_utils.py
00023 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
00024 # ---
00025 
00026 ## @package salome_utils
00027 # \brief Set of utility functions used by SALOME python scripts.
00028 
00029 #
00030 # Exported functions
00031 #
00032 
00033 __all__ = [
00034     'getORBcfgInfo',
00035     'getHostFromORBcfg',
00036     'getPortFromORBcfg',
00037     'getUserName',
00038     'getHostName',
00039     'getShortHostName',
00040     'getAppName',
00041     'getPortNumber',
00042     'getTmpDir',
00043     'getHomeDir',
00044     'generateFileName',
00045     'makeTmpDir',
00046     'uniteFiles',
00047     ]
00048 
00049 # ---
00050 
00051 def _try_bool( arg ):
00052     """
00053     Check if specified parameter represents boolean value and returns its value.
00054     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
00055     are supported.
00056     If <arg> does not represent a boolean, an exception is raised.
00057     """
00058     import types
00059     if type( arg ) == types.BooleanType  :
00060         return arg
00061     elif type( arg ) == types.StringType  :
00062         v = str( arg ).lower()
00063         if   v in [ "yes", "y", "true"  ]: return True
00064         elif v in [ "no",  "n", "false" ]: return False
00065         pass
00066     raise Exception("Not boolean value")
00067 
00068 # ---
00069 
00070 def getORBcfgInfo():
00071     """
00072     Get omniORB current configuration.
00073     Returns a list of three values: [ orb_version, host_name, port_number ].
00074     
00075     The information is retrieved from the omniORB configuration file defined
00076     by the OMNIORB_CONFIG environment variable.
00077     If omniORB configuration file can not be accessed, a list of three empty
00078     strings is returned.
00079     """
00080     import os, re
00081     ret = [ "", "", "" ]
00082     try:
00083         f = open( os.getenv( "OMNIORB_CONFIG" ) )
00084         lines = f.readlines()
00085         f.close()
00086         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
00087         for l in lines:
00088             try:
00089                 m = regvar.match( l )
00090                 if m:
00091                     if m.group(1) is None:
00092                         ret[0] = "4"
00093                     else:
00094                         ret[0] = "3"
00095                         pass
00096                     ret[1] = m.group(2)
00097                     ret[2] = m.group(3)
00098                     break
00099                 pass
00100             except:
00101                 pass
00102             pass
00103         pass
00104     except:
00105         pass
00106     return ret
00107 
00108 # ---
00109 
00110 def getHostFromORBcfg():
00111     """
00112     Get current omniORB host.
00113     """
00114     return getORBcfgInfo()[1]
00115 # ---
00116 
00117 def getPortFromORBcfg():
00118     """
00119     Get current omniORB port.
00120     """
00121     return getORBcfgInfo()[2]
00122 
00123 # ---
00124 
00125 def getUserName():
00126     """
00127     Get user name:
00128     1. try USER environment variable
00129     2. if fails, return 'unknown' as default user name
00130     """
00131     import os
00132     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
00133 
00134 # ---
00135 
00136 def getHostName():
00137     """
00138     Get host name:
00139     1. try socket python module gethostname() function
00140     2. if fails, try HOSTNAME environment variable
00141     3. if fails, try HOST environment variable
00142     4. if fails, return 'unknown' as default host name
00143     """
00144     import os
00145     try:
00146         import socket
00147         host = socket.gethostname()
00148     except:
00149         host = None
00150         pass
00151     if not host: host = os.getenv("HOSTNAME")
00152     if not host: host = os.getenv("HOST")
00153     if not host: host = "unknown"           # 'unknown' is default host name
00154     return host
00155 
00156 # ---
00157 
00158 def getShortHostName():
00159     """
00160     Get short host name:
00161     1. try socket python module gethostname() function
00162     2. if fails, try HOSTNAME environment variable
00163     3. if fails, try HOST environment variable
00164     4. if fails, return 'unknown' as default host name
00165     """
00166     try:
00167         return getHostName().split('.')[0]
00168     except:
00169         pass
00170     return "unknown"           # 'unknown' is default host name
00171     
00172 # ---
00173 
00174 def getAppName():
00175     """
00176     Get application name:
00177     1. try APPNAME environment variable
00178     2. if fails, return 'SALOME' as default application name
00179     """
00180     import os
00181     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
00182 
00183 # ---
00184 
00185 def getPortNumber(use_default=True):
00186     """
00187     Get current naming server port number:
00188     1. try NSPORT environment variable
00189     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
00190     2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
00191     """
00192     import os
00193     try:
00194         return int( os.getenv( "NSPORT" ) )
00195     except:
00196         pass
00197     port = getPortFromORBcfg()
00198     if port is not None: return port
00199     if use_default: return 2809 # '2809' is default port number
00200     return None
00201 
00202 # ---
00203 
00204 def getHomeDir():
00205     """
00206     Get home directory.
00207     """
00208     import os, sys
00209     if sys.platform == "win32":
00210         # for Windows the home directory is detected in the following way:
00211         # 1. try USERPROFILE env variable
00212         # 2. try combination of HOMEDRIVE and HOMEPATH env variables
00213         # 3. try HOME env variable
00214         # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used
00215         dir = os.getenv("USERPROFILE")
00216         if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"):
00217             dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH"))
00218         if not dir:
00219             dir = os.getenv("HOME")
00220         pass
00221     else:
00222         # for Linux: use HOME variable
00223         dir = os.getenv("HOME")
00224         pass
00225     return dir
00226 # ---
00227 
00228 def getTmpDir():
00229     """
00230     Get directory to be used for the temporary files.
00231     """
00232     import os, sys
00233     if sys.platform == "win32":
00234         # for Windows: temporarily using home directory for tmp files;
00235         # to be replaced with TEMP environment variable later...
00236         dir = os.getenv("HOME")
00237     else:
00238         # for Linux: use /tmp/logs/{user} folder
00239         dir = os.path.join( '/tmp', 'logs', getUserName() )
00240         pass
00241     return dir
00242 
00243 # ---
00244 
00245 def generateFileName( dir, prefix = None, suffix = None, extension = None,
00246                       unique = False, separator = "_", hidden = False, **kwargs ):
00247     """
00248     Generate file name by sepecified parameters. If necessary, file name
00249     can be generated to be unique.
00250 
00251     Parameters:
00252     - dir       : directory path
00253     - prefix    : file prefix (not added by default)
00254     - suffix    : file suffix (not added by default)
00255     - extension : file extension (not added by default)
00256     - unique    : if this parameter is True, the unique file name is generated:
00257     in this case, if the file with the generated name already exists
00258     in the <dir> directory, an integer suffix is added to the end of the
00259     file name. This parameter is False by default.
00260     - separator : separator of the words ('_' by default)
00261     - hidden    : if this parameter is True, the file name is prepended by . (dot)
00262     symbol. This parameter is False by default.
00263 
00264     Other keyword parameters are:
00265     - with_username : 'add user name' flag/option:
00266       * boolean value can be passed to determine user name automatically
00267       * string value to be used as user name
00268     - with_hostname : 'add host name' flag/option:
00269       * boolean value can be passed to determine host name automatically
00270       * string value to be used as host name
00271     - with_port     : 'add port number' flag/option:
00272       * boolean value can be passed to determine port number automatically
00273       * string value to be used as port number
00274     - with_app      : 'add application name' flag/option:
00275       * boolean value can be passed to determine application name automatically
00276       * string value to be used as application name
00277     All <with_...> parameters are optional.
00278     """
00279     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
00280     from launchConfigureParser import verbose
00281     filename = []
00282     # separator
00283     if separator is None:
00284         separator = ""
00285         pass
00286     else:
00287         separator = str( separator )
00288         pass
00289     # prefix (if specified)
00290     if prefix is not None:
00291         filename.append( str( prefix ) )
00292         pass
00293     # additional keywords
00294     ### check unsupported parameters
00295     for kw in kwargs:
00296         if kw not in supported and verbose():
00297             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
00298             pass
00299         pass
00300     ### process supported keywords
00301     for kw in supported:
00302         if kw not in kwargs: continue
00303         ### user name
00304         if kw == 'with_username':
00305             try:
00306                 # auto user name ?
00307                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
00308                 pass
00309             except:
00310                 # user name given as parameter
00311                 filename.append( kwargs[kw] )
00312                 pass
00313             pass
00314         ### host name
00315         elif kw == 'with_hostname':
00316             try:
00317                 # auto host name ?
00318                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
00319                 pass
00320             except:
00321                 # host name given as parameter
00322                 filename.append( kwargs[kw] )
00323                 pass
00324             pass
00325         ### port number
00326         elif kw == 'with_port':
00327             try:
00328                 # auto port number ?
00329                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
00330                 pass
00331             except:
00332                 # port number given as parameter
00333                 filename.append( str( kwargs[kw] ) )
00334                 pass
00335             pass
00336         ### application name
00337         elif kw == 'with_app':
00338             try:
00339                 # auto application name ?
00340                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
00341                 pass
00342             except:
00343                 # application name given as parameter
00344                 filename.append( kwargs[kw] )
00345                 pass
00346             pass
00347         pass
00348     # suffix (if specified)
00349     if suffix is not None:
00350         filename.append( str( suffix ) )
00351         pass
00352     # raise an exception if file name is empty
00353     if not filename:
00354         raise Exception("Empty file name")
00355     #
00356     if extension is not None and extension.startswith("."): extension = extension[1:]
00357     #
00358     import os
00359     name = separator.join( filename )
00360     if hidden: name = "." + name                       # add dot for hidden files
00361     if extension: name = name + "." + str( extension ) # add extension if defined
00362     name = os.path.join( dir, name )
00363     if unique:
00364         # create unique file name
00365         index = 0
00366         while os.path.exists( name ):
00367             index = index + 1
00368             name = separator.join( filename ) + separator + str( index )
00369             if hidden: name = "." + name                       # add dot for hidden files
00370             if extension: name = name + "." + str( extension ) # add extension if defined
00371             name = os.path.join( dir, name )
00372             pass
00373         pass
00374     return os.path.normpath(name)
00375 
00376 # ---
00377 
00378 def makeTmpDir( path, mode=0777 ):
00379     """
00380     Make temporary directory with the specified path.
00381     If the directory exists then clear its contents.
00382 
00383     Parameters:
00384     - path : absolute path to the directory to be created.
00385     - mode : access mode
00386     """
00387     import os
00388     if os.path.exists( path ):
00389         import sys
00390         if sys.platform == "win32":
00391             os.system( "rmdir /S /Q " + '"' + path + '"' )
00392             os.system( "mkdir " + '"' + path + '"' )
00393         else:
00394             os.system( "rm -rf " + path + "/*" )
00395     else:
00396         dirs = path.split("/")
00397         shift1 = shift2 = 0
00398         if not dirs[0]: shift1 = 1
00399         if dirs[-1]: shift2 = 1
00400         for i in range(1+shift1,len(dirs)+shift2):
00401             p = "/".join(dirs[:i])
00402             try:
00403                 os.mkdir(p, mode)
00404                 os.chmod(p, mode)
00405             except:
00406                 pass
00407 
00408 # ---
00409 
00410 def uniteFiles( src_file, dest_file ):
00411     """
00412     Unite contents of the source file with contents of the destination file
00413     and put result of the uniting to the destination file.
00414     If the destination file does not exist then the source file is simply
00415     copied to its path.
00416 
00417     Parameters:
00418     - src_file  : absolute path to the source file
00419     - dest_file : absolute path to the destination file
00420     """
00421     import os
00422 
00423     if not os.path.exists( src_file ):
00424         return
00425         pass
00426 
00427     if os.path.exists( dest_file ):
00428         # add a symbol of new line to contents of the destination file (just in case)
00429         dest = open( dest_file, 'r' )
00430         dest_lines = dest.readlines()
00431         dest.close()
00432 
00433         dest_lines.append( "\n" )
00434 
00435         dest = open( dest_file, 'w' )
00436         dest.writelines( dest_lines )
00437         dest.close()
00438 
00439         import sys
00440         if sys.platform == "win32":
00441             command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
00442         else:
00443             command = "cat " + src_file + " >> " + dest_file
00444             pass
00445         pass
00446     else:
00447         import sys
00448         if sys.platform == "win32":
00449             command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
00450         else:
00451             command = "cp " + src_file + " " + dest_file
00452             pass
00453         pass
00454 
00455     os.system( command )
00456 
00457 # --
00458 
00459 _verbose = None
00460 
00461 def verbose():
00462     """
00463     Get verbosity level. Default verbosity level is specified via the environment variable
00464     SALOME_VERBOSE, e.g.:
00465     [bash %] export SALOME_VERBOSE=1
00466     The function setVerbose() can be used to change verbosity level explicitly.
00467     """
00468     global _verbose
00469     # verbose has already been called
00470     if _verbose is not None:
00471         return _verbose
00472     # first time
00473     try:
00474         from os import getenv
00475         _verbose = int(getenv('SALOME_VERBOSE'))
00476     except:
00477         _verbose = 0
00478         pass
00479     #
00480     return _verbose
00481 
00482 def setVerbose(level):
00483     """
00484     Change verbosity level. The function verbose() can be used to get current verbosity level.
00485     """
00486     global _verbose
00487     _verbose = level
00488     return
00489