Linux Expect Tutorial Example Questions

Question:

I am learning how to use the Linux command – Expect following this tutorial.

#!/usr/bin/expect

set timeout 20

spawn "./addition.pl"

expect "Enter the number1 :" { send "12r" }
expect "Enter the number2 :" { send "23r" }

interact

Can anyone here explain what the command below does.

spawn "./addition.pl" 

btw, I cannot find any file called “./additon.pl”, so I can not run the example successfully.

I don’t know how this Perl was written, but I imagine somehow the script (as jvperrin mentioned, it could be any language) should read from standard input and add them up.
I use Python and I tried to write the adder.py.

#!/usr/bin/python 
import sys
print int(sys.argv[1]) + int(sys.argv[2])

but when I change spawn “./add.py” it still doesn’t work…

And the error looks like below:

Traceback (most recent call last):
  File "./add.py", line 3, in <module>
    print int(sys.argv[1]) + int(sys.argv[2])
IndexError: list index out of range
expect: spawn id exp7 not open
    while executing
"expect "Enter the number2 :" { send "23r" }"
    (file "./test" line 8)
Asked By: B.Mr.W.

||

Answers:

Spawn will essentially start a command, so you could use it in any way you would a command. For example, you could use it as spawn "cd .." or spawn "ssh user@localhost" instead of as spawn "./addition.pl".

In this case, the spawn directive starts an interactive perl program in addition.pl and then inputs two values to the program once it has started.

Here is my ruby program, which works fine with expect:

#!/usr/bin/ruby

print "Enter the number1 :"
inp1 = gets.chomp
print "Enter the number2 :"
inp2 = gets.chomp

puts inp1.to_i + inp2.to_i
Answered By: jvperrin

I wrote a C program to substitute the addition.pl.

#include <stdio.h>

int main(int argc, char *argv[]){
    int a, b;
    printf("Enter the number1 :");
    scanf("%d", &a);
    printf("Enter the number2 :");
    scanf("%d", &b);
    printf("%d + %d = %dn", a, b, a+b);
    return 0;
}

Two printf func call is necessary. 🙂

Answered By: Xiaosheng
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.