2016-04-29 17 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. 
$ 

Iはまた、代わりに(/ binに/ bashの)別のシェルを作成する)(pexpect.spawn直接スクリプト(script.py)を通過しようとしています。それは助けになりませんでした。 私は何が間違っているのか分かりません。誰か助言してもらえますか?

ありがとうございました。

答えて

0

あなたのpexpectは正常に動作していますが、まだスポーンオブジェクトからの出力をさらに要求していません。であるとして、あなたが書いたコードを実行する

、私は次のような出力が得られます。

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

$ 

あなたがpexp.pyの終わりに別のpobj.expect()呼び出しを追加する場合は、残りの出力を得ることができます。特に、pexpect検索定数pexpect.EOFを使用すると、spawnオブジェクトはファイルの終わりを探し(スクリプトが完了したとき)、出力をstdoutに記録します。ここに追加して、あなたのコードは次のとおりです。

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


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

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() 

が、これは次の出力を与える実行

関連する問題