To see this problem, you can run the following script. (The shell script will display numbers from 1 to 10 and sleep 1 second after each number. Pexpect will wait 2 seconds for a timeout and print the numbers seen.):
#!/usr/bin/env python import pexpect child = pexpect.spawn('/bin/sh -c "i=0; while [ $i -lt 10 ]:; do echo $((i=i+1)); sleep 1; done"') while True: i=child.expect ([pexpect.TIMEOUT, pexpect.EOF], timeout=2) if i==0: print "before=%s" % child.before else: break
The result will look like this (we also get numbers that have already been read earlier):
before='1\r\n2\r\n' before='1\r\n2\r\n3\r\n4\r\n' before='1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n' before='1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n' before='1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n'
To solve the problem, two lines can be added to the script:
#!/usr/bin/env python import pexpect child = pexpect.spawn('/bin/sh -c "i=0; while [ $i -lt 10 ]:; do echo $((i=i+1)); sleep 1; done"') while True: i=child.expect ([pexpect.TIMEOUT, pexpect.EOF], timeout=2) if i==0: print "before=%s" % repr(child.before) if child.before: child.expect (r'.+') else: break
And the result will be as expected:
before='1\r\n2\r\n' before='3\r\n4\r\n' before='5\r\n6\r\n' before='7\r\n8\r\n' before='9\r\n10\r\n'
bernd source share