期望脚本与 python 命令行应用程序交互

Expect script for interacting with a python command line application

给定一个交互式 python 脚本

#!/usr/bin/python
import sys

name = raw_input("Please enter your name: ")
age = raw_input("Please enter your age: ")
print("Happy %s.th birthday %s!" % (age, name))

while 1:
    r = raw_input("q for quit: ")
    if r == "q":
        sys.exit()

我想通过 expect 脚本与其交互

#!/usr/bin/expect -f

set timeout 3
puts "example to interact"
spawn python app.py

expect {
    "name: " { send "jani\r"; }
    "age: "  { send "12\r"; }
    "quit: " { send "q\r"; }
}

puts "bye"

expect 脚本似乎没有与 python 应用程序交互,只是 运行 在上面。

问题出在 python 还是预期代码上?

你需要的是 3 个不同的 expect 调用:

#!/usr/bin/expect -f

set timeout 3
puts "example to interact"
spawn python app.py

expect "name: " { send "jani\r" }
expect "age: " { send "12\r" }
expect "quit: " { send "q\r" }

原因是 expect 命令不像循环那样工作。一旦它处理了 input/output,它就会继续。

为什么需要expect?

python app.py <<END_INPUT
jani
12
q
END_INPUT