python-streamexpect icon indicating copy to clipboard operation
python-streamexpect copied to clipboard

Provide a "drain"-like method on Expecters

Open mikewadsten opened this issue 9 years ago • 1 comments

I'd like there to be a method on expecters to be able to "drain" any immediately-available data. (And/or to drain through EOF, if there's a way to detect EOF.)

My use case:

  • Spawn (Popen) a testing script which has fairly parseable output
  • Wrap stdout of that process with echo=True (so output is echoed to our stdout)
  • Watch the process's output for specific cues, and respond to those by controlling a USB LED device (https://blink1.thingm.com/)

I currently do this using plain ol' expect. I can achieve the "output is echoed to our stdout" with just log_user 1 in expect, but since streamexpect seems to stop reading once it hits a match, my output will suddenly stop in most cases. Having a drain method which just chomps through any immediately-available data (e.g. poll until nothing comes back immediately, append that to the buffer, chomp through it, done) would let me dump out the rest of the line.

I could work around this by using a RegexSearcher for the error lines (with r'file not found:.*$' as an example) but that's just gross.

In the end I'd like to be able to do something like this:

pipe = Popen(command, shell=True, stdout=PIPE).stdout
with streamexpect.wrap(pipe, echo=True) as stream:
    text = streamexpect.BytesSearcher
    startup = streamexpect.SearcherCollection([
        # Indicates the command is working
        text("Test Setup"),
        # Indications that the command isn't working
        text("file not found:"),
        text("Usage:")
    ])

    match = stream.expect(startup, timeout=5)
    if match.match != "Test Setup":  # Yes this could be improved
        stream.drain()  # Print out any remaining input
        print("Hit a problem.")
        sys.exit(1)

mikewadsten avatar Jan 21 '16 22:01 mikewadsten

Thanks @mikewadsten! This makes perfect sense, and shouldn't be too difficult to implement. I will add it to the queue.

nastevens avatar Jan 22 '16 15:01 nastevens