2016-04-29 110 views
0

我正在嘗試使用pexpect自動交互式python腳本。但是在控制權迴歸到關注點之後,它不會繼續。與pexpect中的python腳本交互

這是一個模擬腳本嘗試模擬相同的事情。

---------------- python script(script.py) ----------------- 
def issue_command(): 
     print "********** in issue_command ********" 

def dummy_check(): 
     print "********** in dummy_check ********" 
     raw_input("Now Press enter for next command") 
     issue_command() 

if __name__ == "__main__": 
    dummy_check() 

--------------------------------Pexpect script(pexp.py)----------------------- 
import pexpect 
import sys 

def quick_test(): 

     pobj = pexpect.spawn("/bin/bash") 
     pobj.logfile = sys.stdout 
     pobj.sendline("script.py") 
     pobj.expect("Now Press enter for next command") 
     print "\n1st part is done. Now execute the oil command" 
     pobj.sendline() 
if __name__ == "__main__": 
    quick_test() 
------------------------------------------------------------------- 

我期望輸出如下。

$python pexp.py 
********** in dummy_check ******** 
Now Press enter for next command -------------------> It should wait here. Upon pressing enter it should print the next line. 
********** in issue_command ******** 
$ 

相反,它不打印二號線即Pexpect的不能用腳本交互 它之間在返回後。

$ python pexp.py 
./script.py 
********** in dummy_check ******** 
Now Press enter for next command -----> It ignored sendline() and did not execute issue_command function. 
$ 

我也試圖通過直接在pexpect.spawn腳本(script.py)(),而不是創建另一個shell程序(/ bin/bash)的。它沒有幫助。 我不知道我在做什麼錯。有人可以請指教嗎?

謝謝。

回答

0

你的pexpect工作正常,但你還沒有要求從spawn對象更多的輸出。

運行你原樣寫的代碼,我得到以下輸出:

********** in dummy_check ******** 
Now Press enter for next command 
1st part is done. Now execute the oil command 

$ 

如果添加另一個pobj.expect()調用的pexp.py末,你可以得到剩餘的輸出。特別是,使用pexpect搜索常量pexpect.EOF將使您的spawn對象查找文件的末尾(腳本完成時)並將輸出記錄到stdout。這裏是你的代碼中加入:

import pexpect 
import sys 

def quick_test(): 
    pobj = pexpect.spawn('/bin/bash') 
    pobj.logfile = sys.stdout 
    pobj.sendline('python script.py') 
    pobj.expect("Now Press enter for next command") 
    print "\n1st part is done. Now execute the oil command" 
    pobj.sendline() 
    pobj.expect(pexpect.EOF) # <-- wait until we hit the end of the file 

if __name__ == '__main__': 
    quick_test() 

運行此給出以下的輸出:

********** in dummy_check ******** 
Now Press enter for next command 
1st part is done. Now execute the oil command 


********** in issue_command ******** 
$