Sharad Sharad - 1 year ago 105
Python Question

Pexpect: Read from the last send

I am trying to read the output of pexpect.send(cmd) but here's the problem I am facing.

I am sending many commands in a sequence and I want to read/expect after a certain set of commands. Condition is that only the output of last command is to be considered. But

matches from the point it last read. I have tried different methods such as matching for an EOF before sending the command of which I need the output but EOF means that child has terminated. I have tried reading till timeout and then sending the command but timeout itself causes the child to terminate.

I have looked for ways in which I could read from the end or the last line of output. I am considering reading a fixed bytes to a file or string and then manipulate the output to get the info I want. Here as well the fixed number of bytes is not fixed. There does not seems to be a reliable way to do this.

Could anyone help me sort this out ?

Answer Source

There are three ways in which this problem can be handled but none to flush the buffer

  1. In Pexpect every send call should be matched with a call to expect. This ensures that the file pointer has moved ahead of the previous send.
  2. If there is a series of send before a single expect then we need to provide a way to move file pointer to the location of last send. This can be done by an extra send whose expect output is unique. The uniqueness should be such that none of the send in the series of send should give that output.
  3. Third method is to use set logfile_read to a file. All the output will be logged to this file. Before the send for which the expect is used, get the position of file pointer. Now get the position of file pointer after the send as well. Search for expected pattern in the file in between first and second pointer.

First method is the ideal way it should be done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download