【问题标题】:Why isn't pexpect consuming the output from the shell properly?为什么 pexpect 不能正确使用 shell 的输出?
【发布时间】:2013-01-08 00:05:49
【问题描述】:

我正在运行 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() 语句使用,但它一直出现。为什么??

【问题讨论】:

    标签: python pexpect


    【解决方案1】:

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

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

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

    之前:JUNK-0 我的机器

    之后:% JUNK-0

    请注意,after不会被完全消耗掉,只有%会消失。因此,在您的下一个期望中,您会得到:

    之前:JUNK-0 JUNK-0:找不到命令。 我的机器

    之后:% JUNK-1

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

    我认为如果换行:

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

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

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多