ATLAS Offline Software
Loading...
Searching...
No Matches
python.logfiles Namespace Reference

Functions

 grep_with_context (f, pattern, lines=100, print_head=True, print_tail=True)

Detailed Description

Utilitites for log file parsing and printing

Function Documentation

◆ grep_with_context()

python.logfiles.grep_with_context ( f,
pattern,
lines = 100,
print_head = True,
print_tail = True )
Print errors in file `f` with the given number of context lines before/after
the `pattern` (regex). In addition print head or tail of file if requested.

Definition at line 10 of file logfiles.py.

10def grep_with_context(f, pattern, lines = 100, print_head = True, print_tail = True):
11 """Print errors in file `f` with the given number of context lines before/after
12 the `pattern` (regex). In addition print head or tail of file if requested.
13 """
14 # See: https://stackoverflow.com/questions/36027227
15
16 # Print first N lines:
17 if print_head:
18 sys.stdout.writelines(itertools.islice(f, lines))
19
20 before = collections.deque(maxlen=lines)
21 skipped = 0 # number of skipped lines
22
23 def printBefore():
24 '''Print the `before` buffer'''
25 nonlocal skipped
26 skipped -= len(before)
27 if skipped > 0:
28 sys.stdout.write('\n[Skipped %d line%s]\n\n' % (skipped, 's' if skipped>1 else ''))
29 sys.stdout.writelines(before)
30 before.clear()
31 skipped = 0
32
33 regex = re.compile(pattern)
34 for line in f:
35 if re.search(regex, line):
36 printBefore()
37 sys.stdout.write(line)
38 sys.stdout.writelines(itertools.islice(f, lines))
39 else:
40 skipped += 1
41 before.append(line)
42
43 # Print the last N lines:
44 if print_tail:
45 printBefore()