在pexpect

时间:2016-04-29 02:48:27

标签: python pexpect

我正在尝试使用pexpect自动化交互式python脚本。但是在控制回到pexpect之后它就不会继续。

这是一个模拟脚本尝试模拟同样的事情。

---------------- 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)。它没有帮助。 我不确定我做错了什么。有人可以建议吗?

感谢。

1 个答案:

答案 0 :(得分: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 ********
$