Search code examples
pythonlinuxexpect

Linux Expect Tutorial Example Questions


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 "12\r" }
expect "Enter the number2 :" { send "23\r" }

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 "23\r" }"
    (file "./test" line 8)

Solution

  • 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