Salome HOME
Improve SALOME logger: customize log file name (add port, user and host ids) to avoid...
[modules/kernel.git] / bin / salome_utilities.py
1 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
2 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either 
6 # version 2.1 of the License.
7
8 # This library is distributed in the hope that it will be useful 
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
11 # Lesser General Public License for more details.
12
13 # You should have received a copy of the GNU Lesser General Public  
14 # License along with this library; if not, write to the Free Software 
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18
19 # ---
20 #
21 # File   : salome_utilities.py
22 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
23 #
24 # ---
25
26 """
27 Set of utility functions used by SALOME python scripts.
28 """
29
30 #
31 # Exported functions
32 #
33 __all__ = [
34     'getUserName',
35     'getHostName',
36     'getAppName',
37     'getPortNumber',
38     'generateFileName'
39     ]
40
41 # ---
42
43 def _try_bool( arg ):
44     """
45     Check if specified parameter represents boolean value and returns its value.
46     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
47     are supported.
48     If <arg> does not represent a boolean, an exception is raised.
49     """
50     import types
51     if type( arg ) == types.BooleanType  :
52         return arg
53     elif type( arg ) == types.StringType  :
54         v = str( arg ).lower()
55         if   v in [ "yes", "y", "true"  ]: return True
56         elif v in [ "no",  "n", "false" ]: return False
57         pass
58     raise "Not boolean value"
59
60 # ---
61
62 def getUserName():
63     """
64     Get user name:
65     1. try USER environment variable
66     2. if fails, return 'unknown' as default user name
67     """
68     import os
69     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
70
71 # ---
72
73 def getHostName():
74     """
75     Get host name:
76     1. try socket python module gethostname() function
77     2. if fails, try HOSTNAME environment variable
78     3. if fails, try HOST environment variable
79     4. if fails, return 'unknown' as default host name
80     """
81     import os
82     try:
83         import socket
84         host = socket.gethostname().split('.')[0]
85     except:
86         host = None
87     if not host: host = os.getenv("HOSTNAME")
88     if not host: host = os.getenv("HOST")
89     if not host: host = "unknown"           # 'unknown' is default host name
90     return host
91
92 # ---
93
94 def getAppName():
95     """
96     Get application name:
97     1. try APPNAME environment variable
98     2. if fails, return 'unknown' as default application name
99     """
100     import os
101     return os.getenv( "APPNAME", "salome" ) # 'salome' is default user name
102
103 # ---
104
105 def getPortNumber():
106     """
107     Get current naming server port number:
108     1. try NSPORT environment variable
109     2. if fails, return 2809 as default port number
110     """
111     import os
112     return os.getenv( "NSPORT", 2809 )      # '2809' is default port number
113
114 # ---
115
116 def generateFileName( dir, prefix, suffix = None, extension = None,
117                       unique = False, separator = "_", **kwargs ):
118     """
119     Generate unique file name.
120
121     The following parameters are supported:
122     <dir> - directory for the tmp file
123     <prefix> - file prefix
124     <suffix> - file suffix (not added by default)
125     <extension> - file extension (not added by default)
126     <separator> - separator of the words ('_' by default)
127     <with_username> 'add user name' flag/option:
128     - boolean value can be passed to determine user name automatically
129     - string value to be used as user name
130     <with_hostname> 'add host name' flag/option:
131     - boolean value can be passed to determine host name automatically
132     - string value to be used as host name
133     <with_port> 'add port number' flag/option:
134     - boolean value can be passed to determine port number automatically
135     - string value to be used as port number
136     <with_appname> 'add application name' flag/option:
137     - boolean value can be passed to determine application name automatically
138     - string value to be used as application name
139     All <with_...> parameters are optional.
140     <unique> If this parameter is True the unique file name is generated:
141     in this case, if the file with the generated name already exists
142     in the <dir> directory, an integer suffix is added to the end of
143     file name. This parameter is False by default.
144     """
145     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
146     from launchConfigureParser import verbose
147     filename = []
148     # separator
149     if separator is None:
150         separator = ""
151         pass
152     else:
153         separator = str( separator )
154         pass
155     # prefix (if specified)
156     if prefix:
157         filename.append( str( prefix ) )
158         pass
159     # additional keywords
160     ### check unsupported parameters
161     for kw in kwargs:
162         if kw not in supported and verbose():
163             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
164             pass
165         pass
166     ### process supported keywords
167     for kw in supported:
168         if kw not in kwargs: continue
169         ### user name
170         if kw == 'with_username':
171             try:
172                 # auto user name ?
173                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
174                 pass
175             except:
176                 # user name given as parameter
177                 filename.append( kwargs[kw] )
178                 pass
179             pass
180         ### host name
181         elif kw == 'with_hostname':
182             try:
183                 # auto host name ?
184                 if _try_bool( kwargs[kw] ): filename.append( getHostName() )
185                 pass
186             except:
187                 # host name given as parameter
188                 filename.append( kwargs[kw] )
189                 pass
190             pass
191         ### port number
192         elif kw == 'with_port':
193             try:
194                 # auto port number ?
195                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
196                 pass
197             except:
198                 # port number given as parameter
199                 filename.append( str( kwargs[kw] ) )
200                 pass
201             pass
202         ### application name
203         elif kw == 'with_app':
204             try:
205                 # auto application name ?
206                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
207                 pass
208             except:
209                 # application name given as parameter
210                 filename.append( kwargs[kw] )
211                 pass
212             pass
213         pass
214     # suffix (if specified)
215     if suffix:
216         filename.append( str( suffix ) )
217         pass
218     # raise an exception if file name is empty
219     if not filename:
220         raise "Empty file name"
221     # create unique file name
222     import os
223     name = os.path.join( dir, separator.join( filename ) )
224     if extension: name += str( extension )
225     if unique:
226         index = 0
227         while os.path.exists( name ):
228             index = index + 1
229             name = os.path.join( dir, separator.join( filename ) + separator + str( index ) )
230             if extension: name += str( extension )
231             pass
232         pass
233     return name