TDN169 TDN169 - 27 days ago 19
Python Question

Use pexpect to detect end of bash output

I am using

pexpect
to run a bash instance:

bash = pexpect.spawn("/bin/bash")


I would like to be able to "expect" the end of this output. At the moment I'm using the following:

bash.sendline("ls -ltr")
lines = []
while True:
try:
bash.expect("\r\n", timeout=0.1)
lines.append(bash.before)
except pexpect.TIMEOUT:
print "TO"
break


This is effective, however it seems like it would be more efficient to be able to detect the end of the output without needing to wait for pexpect.TIMEOUT.

Answer

You should expect your prompt. Say your prompt is "s", your code should be :

bash.expect(">")

or even set a variable first for your prompt (in case later on you want to change your prompt;))

prompt = ">"
bash.expect(prompt)