10 def 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.
18 sys.stdout.writelines(itertools.islice(f, lines))
20 before = collections.deque(maxlen=lines)
24 '''Print the `before` buffer'''
26 skipped -= len(before)
28 sys.stdout.write(
'\n[Skipped %d line%s]\n\n' % (skipped,
's' if skipped>1
else ''))
29 sys.stdout.writelines(before)
33 regex = re.compile(pattern)
35 if re.search(regex, line):
37 sys.stdout.write(line)
38 sys.stdout.writelines(itertools.islice(f, lines))