2016-04-29 108 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 ******** 
$