9

I am using Pexpect module to connect to remote server. I can successfully send and retrieve response. I am trying to clear a buffer by expecting something junk and assuming it will clear the buffer but actually it is not clearing the buffer.

Below is my sample code

import pexpect
obj = pexpect.spawn("telnet 172.16.250.250", maxread=8192)

obj.sendline("")
result = obj.expect(expected, timeout=3) --> getting output here `OUTPUT 1`
obj.sendline("1")
time.sleep(3)
try:
    obj.expect("Asdfgdsad", timeout=2)  --> I am expecting to clear buffer here but it did not

except pexpect.TIMEOUT:
    pass
print("buffer is", obj.buffer) . --> This is printing output `OUTPUT 1` as I have meniotned

I am doing something wrong here?? I am using python3.7 . If I remember correctly It was working correctly in python2.X

Sumit
  • 1,953
  • 6
  • 32
  • 58

2 Answers2

4

You can clear pexpects buffer by explicitly reading it, IIRC.

flush = ''
while not obj.expect(r'.+', timeout=5):
    flush += obj.match.group(0)
Aiyion.Prime
  • 973
  • 9
  • 20
0
  • ".+" tries to grab one or more bytes from buffer, thus cleaning eveything if there is something.
  • we run the while loop to read until there is nothing.
  • since timeout is zero, it returns immediatly if there is nothing, but raises exception, which is where loop terminates.
try:
    while True:
        session.expect(r'.+', timeout=0)
except (pexpect.TIMEOUT, pexpect.EOF) as e:
    pass
Prabhu U
  • 304
  • 1
  • 4
  • 9