Python how to read output from pexpect child?

user2579116 picture user2579116 · Jul 13, 2013 · Viewed 101k times · Source
child = pexpect.spawn ('/bin/bash')
child.sendline('ls')
print(child.readline())
print child.before, child.after

All I get with this code in my output is

ls

ls 

But when my code is

child = pexpect.spawn('ls')
print(child.readline())
print child.before, child.after

Then it works, but only for the first 2 prints. Am I using the wrong send command? I tried send, write, sendline, and couldn't find anymore.

Answer

Catalin Luta picture Catalin Luta · Jul 16, 2013

In pexpect the before and after attributes are populated after an expect method. The most common thing used in this situation is waiting for the prompt (so you'll know that the previous command finished execution). So, in your case, the code might look something like this:

child = pexpect.spawn ('/bin/bash')
child.expect("Your bash prompt here")
child.sendline('ls')
#If you are using pxssh you can use this
#child.prompt()
child.expect("Your bash prompt here")
print(child.before)