#!/usr/local/bin/python

import os, sys

import re, ExpectPy
ExpectPy.settings.loguser = 0
ExpectPy.settings.full_buffer = 1

def print_line(filename):
  return lambda match, file=filename: sys.stdout.write(file+": "+match)

if __name__ == '__main__':
  pattern = sys.argv[1]
  pattern = '^.*(%s).*\n' % pattern
  regex = re.compile(pattern)
  if len(sys.argv) > 2:
    filelist = map(open, sys.argv[2:])
  else:
    filelist = [sys.stdin]

  last_buffer = ''
  for file in filelist:
    id = ExpectPy.spawnfile(file)
    print id
    func = print_line(file.name)
    try:
      while 1:
        try:
          id.expect((ExpectPy.COMPILED, regex, func))
          last_buffer = ''
        except ExpectPy.full_buffer:
          last_buffer = last_buffer + id.buffer
    except EOFError:
      pass

