17 def search_within_stream(input_stream, pattern, default=None):
18 """Search for regular expression in a file-like object.
19
20 Opens a file for reading and searches line by line for a match to
21 the regex and returns the parenthesized group named return for the
22 first match. Does not search across newlines.
23
24 For example:
25 pattern = '^root(:[^:]*){4}:(?P<return>[^:]*)'
26 with open('/etc/passwd', 'r') as stream:
27 return search_within_file(stream, pattern)
28 should return root's home directory (/root on my system).
29
30 Args:
31 input_stream: file-like object to be read
32 pattern: (string) to be passed to re.compile
33 default: what to return if no match
34
35 Returns:
36 A string or whatever default is
37 """
38 pattern_object = re.compile(pattern)
39 for line in input_stream:
40 match = pattern_object.search(line)
41 if match:
42 return match.group('return')
43 return default
44