如何获得expect中spawn的命令的返回值?

如何获得expect中spawn的命令的返回值?

我们写一个名为test.exe的小程序,程序的源码如下:

#include 
#include 
#include 
int main(int argc, char* argv[])
{
    std::cout << "please input data:" << std::endl;
    std::string data;
    std::getline(std::cin, data);
    int ret = atoi(data.c_str());
    std::cout << "input data :" << data << std::endl;
    std::cout << "will return:" << ret << std::endl;
    return ret;
}
我们写一个脚本:

#!/usr/bin/expect
spawn test.exe
expect "please input data:"
send "110\n"
expect eof
catch wait result
exit [lindex $result 3]
解释:
第6行:catch wait result
解释:将wait命令的返回值存储到result变量中. result变量并不是一个特殊变量, 你可以随意换一个新名字(比如retVal).
备注:wait命令的返回值是一个"%d %s 0 %d"格式的字符串,第0个值是pid,第1个是spawn_id(不知道它具体带表了什么),第2个应当是代表脚本是否正常完成,第3个是子进程的返回值.
第7行:exit [lindex $result 3]
将result变量(这个变量存储的是一个列表)list中的index=3的那个值取出来,返回它。你可以搜索"Tcl 列表 lindex"以查看详细信息。

怎么在一个shell脚本中嵌进去expect的调用?

例子:

#!/bin/bash
DATA="120"
echo "variable is ${DATA}"
echo "will call expect."
expect -c '
spawn test.exe
expect "please input data:"
send '${DATA}'\n
expect eof
catch wait result
exit [lindex $result 3]
'
echo "call expect finish."

未完待续。

我这样写,为什么无法执行?

#!/usr/bin/expect
spawn test.exe
expect {
    "data:" {
        send_user "find [data:], will send data."
        send "119\r"
        exp_continue
    }
    eof {
        send_user "find [eof]."
    }
}
send_user "all done..."
我也不知道,正在解决中。。。

你可能感兴趣的:(Linux)