Normally, the last value in each expect clause is an integer to be returned. But it is also possible to place a callable object there instead. This allows you to perform some processing without having to test the return value when expect ends.


The callback should take one argument, which is the string matched, the object's match attribute. The function can return any Python object, this value will be returned by the expect method. Callbacks in COMPILED clauses are passed a second argument: the regular expression object passed in the clause.


The cont method allows a callback to signal that the expect method reevaluates the clauses passed to it.


Send the matched string to stdout.
obj.expect((ExpectPy.GLOB, "*", sys.stdout.write))
Append the string to a list.
file = []
obj.expect((ExpectPy.GLOB, "*",
  lambda s, l=file: l.append(s))
Return a tuple when we see a date:
date_re = ExpectPy.compile('([0-9][0-9])/([0-9][0-9])/([0-9][0-9])')
def get_date(line, pattern):
  if ExpectPy.re_type == 'tclre':
    return tuple(pattern[1:4])
    return tuple(, 2, 3))
value = obj.expect(
  (ExpectPy.COMPILED, date_re, get_date),
  (ExpectPy.GLOB, "?*", sys.stderr.write)
if type(value) is TupleType:
  print "The date is %s/%s/%s" % value