簡體   English   中英

為什么pexpect無法正確使用shell的輸出?

[英]Why isn't pexpect consuming the output from the shell properly?

我正在運行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()語句使用它,但是它一直顯示。 為什么??

在您發布的示例中發生的是對pexpect輸出的不正確處理。 當Pexpect的認定,預計表達式匹配的東西,它填充比賽 用正確的值的字段。 來自pexpect文檔的報價可能會有所幫助:

找到匹配項后,將設置實例屬性'before','after'和'match'。您可以在'before'中看到在匹配項之前讀取的所有數據。您可以在'after'中看到已匹配的數據。重新匹配中使用的re.MatchObject將處於'match'中。如果發生錯誤,則將'before'設置為到目前為止讀取的所有數據,'after'和'match'將為None。

在您的情況下,第一個期望產生以下結果:

之前 :JUNK-0 myMachine

之后 :%JUNK-0

請注意,不會完全消耗完之后,只有%會消失。 因此,在您的下一個期望中,您將獲得:

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

之后 :%JUNK-1

據我所知,第一個期望值(超時,超出了for循環)不會消耗輸出。

我認為,如果您更改行:

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

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

輸出將同步,您將獲得正確的輸出。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM