initial checkin
[grml-etc.git] / etc / skel / .wmi / szs2.1 / szstoolbox.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Title:        toolbox for szs script
5 # Date:         Saturday 6th of November 2004
6 # Author:       Norman Köhring
7 # License:      GPL
8
9 from sys import argv
10 from os import chdir,getenv
11 from os.path import dirname,abspath
12 from os.path import exists as fexists
13 from time import strftime,time
14 import inspect
15 chdir(dirname(abspath(argv[0])))
16
17
18
19 class Error(Exception):
20         """A general Exception which can be used/inherited 
21            from any module""" 
22         def __init__(self, reason):
23                 self.reason = reason
24         def __str__(self):
25                 return repr(self.reason)
26
27
28
29 class MSG:
30         """ all functions to give messages to whatever
31             this class contains: help, debug, say and log """
32
33         
34         def ___init___(self):
35                 """ initializes the variables """
36
37                 self.message = ''
38                 self.place = ''
39                 self.msgcache = []
40                 
41         
42         
43
44         def usage(self, modname = None, modtxt = None):
45                 """ prints a helpmessage to stdout
46                     Usage: msg.usage([modulename [, moduletext ]])
47                     Returns: nothing """
48                 
49                 print progname+progver
50                 if modname:
51                         print "Module:"+ str(modname)
52                 
53                 if modtxt:
54                         print modtxt
55                 else:
56                         print """
57                         Usage:
58                         ./szs.py
59
60                         No parameters at the moment.
61                         For configurations look at szs.cfg,
62                         for more help look at README.
63                         """
64         
65
66         
67         def debug(self, msg, lvl):
68                 """ prints debugmessages if lvl >= debuglvl
69                     Usage: debug(message, lvl, source)
70                     Returns: True and prints the debugmessage """
71
72                 if lvl <= debuglevel: # and x == 0:
73                         src = inspect.getouterframes(inspect.currentframe())[1]
74                         prefix = ['Critical: ', 'Warning: ', 'Debug: '][lvl-1]
75                         MSG.log(self, prefix+str(src)+': '+msg)
76                         print prefix+src[1].split('/')[-1].split('.')[0]+': '+src[3]+'(): '+msg
77
78                 return True
79 #                       if cache.get(src) <> None and msg not in cache.get(src)\
80 #                          or cache.get(src) == None:
81 #                               MSG.log(self, str(src)+": "+msg)
82 #                               print 'Debug from '+str(src)+': '+msg
83 #
84 #                       if cache.has_key(src):
85 #                               if cache.get(src).has_key(msg):
86 #                                       cache.get(src).__setitem__(msg,cache.get(src).get(msg)+1)
87 #                               else:
88 #                                       cache.get(src).__setitem__(msg,1)
89 #                       else:
90 #                               cache.__setitem__(src,{msg:1})
91 #
92 #                       return True
93 #
94 #               elif x == 2:
95 #                       MSG.log(self, str(src)+": "+msg)
96 #                       print 'Debug from '+str(src)+': '+msg
97 #               
98 #               elif x == 1:
99 #                       MSG.log(self, "...", True)
100 #                       return cache
101 #               else:
102 #                       return False
103         
104
105
106         def say(self, dict, msg):
107                 """ dont use it... froze this funtion till next release """
108
109                 print "DONT USE THIS FUNCTION (see README for more details)"
110                 return None 
111         
112
113
114         def log(self, msg, write=False, msgcache=[]):
115                 """ sends messages to the configured logfile
116                     should only be used by 'debug' """
117
118                 
119                 time = strftime('%a%d%b%y %X') 
120                 if len(msg) > 0 and msg not in msgcache:
121                         if write:
122                                 F = open(logfile, 'a')          
123                                 F.writelines(msgcache)
124                                 F.close()
125                         else:
126                                 msgcache.append(time+': '+msg+'\n')
127         
128
129
130 class CFG:
131         """ functions for reading and writing the config """
132
133
134         def __init__(self, group):
135                 
136                 self.value = ''
137                 self.group = group
138
139                 cfgR = file(cfgF,'r')
140                 self.cfgL = cfgR.readlines()
141                 cfgR.close()
142         
143
144
145         def __call__(self, group):
146
147                 self.group = group
148                 return self
149
150
151
152         def settings(self):
153                 """ returns the actual settings
154                     Usage: cfg.settings()
155                     Returns: ['value','group','cfgF path'] """
156
157
158                 return [self.value, self.group, cfgF.name]
159         
160
161
162         def read(self, value):
163                 """ reads the configurationfile and returns the values
164                     Usage: cfg.read(value)
165                     Returns: whats inside value """
166
167
168                 self.value = value
169                 lst = []
170
171                 for part in self.cfgL:
172                         if part.find('#') < 0:
173                                 if part.split('=')[0] == self.group+'.'+self.value:
174                                         lst.append(part.split('=')[1].strip('\n'))
175                         elif part.find('#') > 0:
176                                 part = part.split('#')[0]
177                                 if part.split('=')[0] == self.group+'.'+self.value:
178                                         lst.append(part.split('=')[1].strip('\n'))
179                 if len(lst) > 1:
180                         return lst
181                 elif len(lst) == 1:
182                         return lst[0]
183                 else:
184                         return None
185         
186
187
188         def write(self, value):
189                 """ this function does nothing at the moment
190                     in future it writes into the configfiles
191                     ...it is maybe planned for third release """
192
193
194                 print "Damn fnords!"
195         
196
197
198 class XTRA:
199         """ some extra functions like counters """
200
201         def __init__(self):
202                 """ yeah... the init... """
203                 
204                 self.cache = {}
205
206
207         def countadd(self, y=1, x=[0]):
208                 """ counter for addition; Usage: xtra.countadd([y [,x ]])
209                     where y (standard 1) is the value to add to x
210                     Returns: the new value of x """
211
212                 x[0] += y
213                 return x[0]
214         
215
216
217         def countsub(self, y=1, x=[0]):
218                 """ counter for substraction
219                     Usage: xtra.countsub([y ],x ]),
220                     where y (standard 1) is the value to substract from x
221                     Returns: the new value of x """
222
223                 x[0] -= y
224                 return x[0]
225
226
227
228         def strrotate(self, t, l, x=[0]):
229                 """ trying to build a string rotator
230                     Usage: xtra.strrotate(str, length)
231                     where 'str' is the String to rotate in
232                     'length' units
233                     Returns: part of str """
234
235                 if x[0] <= len(t):
236                         x[0] += 1
237                 else:
238                         x[0] = 0
239                 
240                 ret = [x[0],t[x[0]:x[0]+l]]
241                 return ret 
242
243
244
245         def savevar(self, name, value):
246                 """ saves variables in the cache, so your module
247                     can use it later again...
248                     Usage: xtra.savevar(name, value)
249                     Returns: Boolean """
250
251                 self.cache[name] = value
252                 if self.cache.has_key(name):
253                         return True
254                 else:
255                         return False
256         
257
258
259         def getvar(self, name):
260                 """ returns the value of name
261                     Usage: xtra.getvar(name)
262                     Returns: value of name """
263
264                 return self.cache[name]
265
266
267         
268         def delvar(self, name):
269                 """ deletes the variable from list
270                     Usage: xtra.delvar(name)
271                     Returns: Boolean """
272
273                 del self.cache[name]
274                 if self.cache.has_key(name):
275                         return False
276                 else:
277                         return True
278
279
280
281 global cfgF
282 global logfile
283 global accuracy
284 global interval
285 global debuglevel
286 global cfgG
287 global starttime
288
289 if fexists(getenv('HOME')+'/.wmi/szs.cfg'):
290         cfgF = getenv('HOME')+'/.wmi/szs.cfg'
291 else:
292         cfgF = 'szs.cfg'
293 cfg = CFG('')
294 cfgG = cfg('global')            
295 starttime = time()
296
297 logfile = cfgG.read('logfile').strip()
298 debuglevel = int(cfgG.read('debuglevel').strip())
299 accuracy = int(cfgG.read('accuracy').strip())
300 interval = float(cfgG.read('interval').strip())
301
302 # determine kernel version
303 fd = open('/proc/version')
304 kernel_version = fd.readline()[14:20]
305 fd.close()
306