The following script calls an external program and interact with this external program by controlling the inputs and outputs of it.
The script first create call the external program 'dc', which is a postfix based calculator.
Then it send the string "4p\r" as input to the 'dc' program.
In the expect block, the script try to match two patterns: "0\r" and any digit followed by a carry return.
If the output of 'dc' is 0, then the script terminates it by sending the command "q".
If the output of 'dc' is any digit larger then 0 (starting from 4 in this example), the value will be decreased by sending "1-p" to 'dc'.
#!/usr/bin/expect -f
spawn dc
send "4p\r"
expect {
"0\r" {
puts "Expect: matched $expect_out(0,string)";
send "q\r"
puts "Expect: exit";
}
-re {[1-9]\r} {
puts "Expect: matched $expect_out(0,string)";
send "1-p\r";
puts "Expect: reduce by 1";
exp_continue
}
}
Running the script will generated the following output on screen.
$ ./script.exp
spawn dc
4p
4
Expect: matched 4
Expect: reduce by 1
1-p
3
Expect: matched 3
Expect: reduce by 1
1-p
2
Expect: matched 2
Expect: reduce by 1
1-p
1
Expect: matched 1
Expect: reduce by 1
1-p
0
Expect: matched 0
Expect: exit
Notes:
1. Except captures all output from the external program including '\r'.
2. Variable $expect_out(0,string) stores the matched string from the immediate previous matching.
3. Variable $expect_out(buffer) stores the remaining output of the external program by removing all characters up to (and including) the matched string from the immediate previous matching.
The script first create call the external program 'dc', which is a postfix based calculator.
Then it send the string "4p\r" as input to the 'dc' program.
In the expect block, the script try to match two patterns: "0\r" and any digit followed by a carry return.
If the output of 'dc' is 0, then the script terminates it by sending the command "q".
If the output of 'dc' is any digit larger then 0 (starting from 4 in this example), the value will be decreased by sending "1-p" to 'dc'.
#!/usr/bin/expect -f
spawn dc
send "4p\r"
expect {
"0\r" {
puts "Expect: matched $expect_out(0,string)";
send "q\r"
puts "Expect: exit";
}
-re {[1-9]\r} {
puts "Expect: matched $expect_out(0,string)";
send "1-p\r";
puts "Expect: reduce by 1";
exp_continue
}
}
Running the script will generated the following output on screen.
$ ./script.exp
spawn dc
4p
4
Expect: matched 4
Expect: reduce by 1
1-p
3
Expect: matched 3
Expect: reduce by 1
1-p
2
Expect: matched 2
Expect: reduce by 1
1-p
1
Expect: matched 1
Expect: reduce by 1
1-p
0
Expect: matched 0
Expect: exit
Notes:
1. Except captures all output from the external program including '\r'.
2. Variable $expect_out(0,string) stores the matched string from the immediate previous matching.
3. Variable $expect_out(buffer) stores the remaining output of the external program by removing all characters up to (and including) the matched string from the immediate previous matching.
No comments:
Post a Comment