comparison mx/outputparser.py @ 4151:cb22fcb2e2fc

missing file
author Gilles Duboscq <gilles.m.duboscq@gmail.com>
date Tue, 20 Dec 2011 15:48:29 +0100
parents
children a2caa019ba3a
comparison
equal deleted inserted replaced
4150:c78bace5086a 4151:cb22fcb2e2fc
1 import mx
2 import commands
3
4 class OutputParser:
5
6 def __init__(self, nonZeroIsFatal=True):
7 self.matchers = []
8 self.nonZeroIsFatal = nonZeroIsFatal
9
10 def addMatcher(self, matcher):
11 self.matchers.append(matcher)
12
13 def parse(self, cmd, cwd=None):
14 ret = [{}]
15
16 def parseLine(line):
17 line = line.strip()
18 anyMatch = False
19 for matcher in self.matchers:
20 parsed = matcher.parse(line)
21 if parsed:
22 anyMatch = True
23 if matcher.startNewLine and len(ret[0]) > 0:
24 ret.append({})
25 ret[len(ret)-1].update(parsed)
26 if anyMatch :
27 mx.log(line)
28 else :
29 mx.log('# ' + line)
30
31 commands.vm(cmd, nonZeroIsFatal=self.nonZeroIsFatal, out=parseLine, err=parseLine, cwd=cwd)
32 return ret
33
34 class Matcher:
35
36 def __init__(self, regex, valuesToParse, startNewLine=False):
37 assert isinstance(valuesToParse, dict)
38 self.regex = regex
39 self.valuesToParse = valuesToParse
40 self.startNewLine = startNewLine
41
42 def parse(self, line):
43 match = self.regex.search(line)
44 if not match:
45 return False
46 ret = {}
47 for key, value in self.valuesToParse.items():
48 ret[self.parsestr(match, key)] = self.parsestr(match, value)
49 return ret
50
51 def parsestr(self, match, key):
52 if isinstance(key, tuple):
53 if len(key) != 2:
54 raise Exception('Tuple arguments must have a lenght of 2')
55 tup1, tup2 = key
56 # check if key is a function
57 if hasattr(tup1, '__call__'):
58 return tup1(self.parsestr(match, tup2))
59 elif hasattr(tup2, '__call__'):
60 return tup2(self.parsestr(match, tup1))
61 else:
62 raise Exception('Tuple must contain a function pointer')
63 elif key.startswith('const:'):
64 return key.split(':')[1]
65 else:
66 return match.group(key)