为什么pexpect没有正确地消耗shell的输出?

时间:2012-12-26 20:20:55

标签: python pexpect

我正在运行Solaris 5-10,python 2.6.2和pexpect 2.4

我在下面有一个非常简单的python脚本,它练习了从shell发送和接收文本的功能。

我的理解是pexepect([pexpect.TIMEOUT,x,y,z],timeout = w)将返回自上次调用pexpect以来找到的匹配的索引,但如果花费的时间超过w秒,它将返回0.

这是我非常简单的脚本:

#!/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" 

仅供参考,我的shell提示符是“myMachine%”,但是在这个脚本中我只是使用“%”来保持它的通用性。

当我运行它时,我看到以下输出:

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 
================================================================================ 

为什么我会在输出中看到“JUNK-0”一再出现?它应该被第一个myShell.expect()语句使用,但它会一直显示出来。为什么??

1 个答案:

答案 0 :(得分:0)

您发布的示例中发生的情况是对pexpect输出的错误处理。当pexpect找到与期望表达式匹配的内容时,它会填充 之前的字段 匹配 之后的正确值。来自pexpect文档的引用可能有所帮助:

找到匹配后,将设置”之前“,”之后“和”匹配“的实例属性。您可以在”之前“看到匹配前读取的所有数据。您可以看到数据在'after'中匹配。重新匹配中使用的re.MatchObject将处于'匹配'。如果发生错误,那么'before'将被设置为到目前为止所读取的所有数据以及'after'和'match'将是无。

在您的情况下,第一个期望产生以下结果:

在之前

:JUNK-0 MYMACHINE

:%JUNK-0

之后

请注意,在不完全消耗后,只有%会消失。因此,在你的下一个期待你得到:

之前

:JUNK-0 JUNK-0:未找到命令。 MYMACHINE

:%JUNK-1

之后

据我所知,第一个期望(超时,超出for循环)不会消耗输出。

我认为如果你换行:

myShell.expect([pexpect.TIMEOUT], timeout=1)

myShell.expect([pexpect.TIMEOUT, myPrompt], timeout=1)

输出将同步,您将获得正确的输出。

希望这有帮助。