expect - Programmed dialogue with interactive streams



pip install xpect

Example usage

See the test suite: https://github.com/eerimoq/expect/blob/master/tests/test_expect.py

A basic login example using pyserial:

>>> import pyserial
>>> import expect
>>> serial_linux = pyserial.Serial("/dev/ttyS0")
>>> linux = expect.Handler(serial_linux)
>>> linux.send("")
>>> linux.expect(r"username: ")
>>> linux.send("root")
>>> linux.expect(r"password: ")
>>> linux.send("root")
>>> linux.expect(r"/home/root $ ")


class expect.Handler(iostream, eol='n', break_conditions=None, print_input=True, print_output=False, split_pattern='n')[source]

Class wrapping an io object.

__init__(iostream, eol='\n', break_conditions=None, print_input=True, print_output=False, split_pattern='\n')[source]

Initialize object with given parameters.

  • iostream – Io stream to read data from and write data data to. The class of this object must implement two functions, read(count) and write(string). read() must return a string.
  • eol – ‘end of line’ string to send after the ‘send string’.
  • break_conditions – expect() throws an exception if the returned value from iostream.read() is in this iterable.
  • print_input – Print input on stdout.
  • print_output – Print output on stdout.
  • split_pattern – Split read data using this regexp before sreaching for a match.
expect(pattern, timeout=None, print_input=True)[source]

Returns when regular expression pattern matches the data read from the output stream.

Parameters:pattern – Regular expression to match.
Returns:The matched string.
send(string, send_eol=True)[source]

Writes a string to the iostream.

  • string – String to send.
  • send_eol – Send ‘end of line’ after string.

Return value of iostream.write().