我正在使用 Pexpect 模塊連接到遠程服務器。我可以成功發送和檢索響應。我試圖通過期待一些垃圾來清除緩沖區,并假設它會清除緩沖區,但實際上它并沒有清除緩沖區。下面是我的示例代碼import pexpectobj = 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 notexcept pexpect.TIMEOUT: passprint("buffer is", obj.buffer) . --> This is printing output `OUTPUT 1` as I have meniotned我在這里做錯了什么??我正在使用 python3.7 。如果我沒記錯的話它在 python2.X 中正常工作
2 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
您可以通過顯式讀取 IIRC 來清除 pexpects 緩沖區。
flush = ''
while not obj.expect(r'.+', timeout=5):
flush += obj.match.group(0)

呼如林
TA貢獻1798條經驗 獲得超3個贊
".+" 試圖從緩沖區中獲取一個或多個字節,因此如果有什么東西就清理掉所有東西。
我們運行 while 循環來讀取,直到什么都沒有。
由于超時為零,如果沒有任何內容,它會立即返回,但會引發異常,這是循環終止的地方。
try:
while True:
session.expect(r'.+', timeout=0)
except (pexpect.TIMEOUT, pexpect.EOF) as e:
pass
添加回答
舉報
0/150
提交
取消