Why is pexpect acting funny with sendline() and expect()?

saqib.ali.75 at gmail.com saqib.ali.75 at gmail.com
Wed Dec 26 21:19:04 CET 2012


I am running Solaris 5-10, python 2.6.2 and pexpect 2.4

I have the very simple python script below which exercises the functionality of sending and receiving text from the shell.

My understanding is that pexepect([pexpect.TIMEOUT, x,y,z], timeout=w) will return the index of the match that it found *since the last time pexpect was called*, but if it takes longer than w seconds, it will return 0.


Here is my very simple script:


#!/usr/bin/env python

import pexpect
myPrompt = " % "

myShell = pexpect.spawn("/bin/tcsh")
print "Sending 'JUNK-0' to shell"
x = myShell.sendline("JUNK-0")
y = myShell.expect([pexpect.TIMEOUT], timeout=1)               
print "y = %s" % y
print myShell.before 
print "=" * 80
print "\n\n"
 
for i in range(2):
    print "i = %d" % (i+1)
    print "Sending 'JUNK-%d' to shell" % (i+1)
    x = myShell.sendline("JUNK-%d" % (i+1))
    y = myShell.expect([pexpect.TIMEOUT, myPrompt], timeout=10)              
    print "y = %s" % y
    print myShell.before
    print "=" * 80
    print "\n\n"



FYI, my shell prompt is "myMachine % ", however in this script I have simply used " % " to keep it generic.
    
When I run it, I see the following output: 




Sending 'JUNK-0' to shell
y = 0
JUNK-0
myMachine % JUNK-0
JUNK-0: Command not found.
myMachine % 
================================================================================



i = 1
Sending 'JUNK-1' to shell
y = 1
JUNK-0
myMachine 
================================================================================



i = 2
Sending 'JUNK-2' to shell
y = 1
JUNK-0
JUNK-0: Command not found.
myMachine 
================================================================================




Why do I see "JUNK-0" consistently recurring in the output? It should be consumed by the first myShell.expect() statement, but it keeps showing up. Why??



More information about the Python-list mailing list