如何从期望中获得输出

时间:2010-06-07 11:31:11

标签: tcl

我写了一个产生bc命令

的脚本
package require Expect

proc bc {eq} {
    spawn e:/GnuWin32/bc/bin/bc
    send "$eq\r"
    expect -re "(.*)\r"
    return "$expect_out(0,string)"
}

set foo "9487294387234/sqrt(394872394879847293847)"

puts "the valule [bc $foo]"

如何从中获取输出。当我运行这个时,我得到像这样的输出

bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
9487294387234/sqrt(394872394879847293847)
477
can't read "expect_out(0,string)": no such element in array
    while executing
"return "The values is $expect_out(0,string)""
    (procedure "bc" line 6)
    invoked from within
"bc $foo"
    invoked from within
"puts "the valule [bc $foo]""
    (file "bc.tcl" line 21)

如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

问题在于它与您的期望不符。 (提示Jamie Zawinski引用。)

试试这个:

package require Expect
proc bc eq {
    spawn bc; # It's on my path...
    send $eq\r
    set timeout 1; # 1 second
    expect timeout {} -re {[^\r\n]+} {
        set lastline $expect_out(0,string)
        exp_continue
    }
    close
    return $lastline
}
puts >>[bc 9487294387234/sqrt(394872394879847293847)]<<

我得到了这个输出......

spawn bc
9487294387234/sqrt(394872394879847293847)
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
9487294387234/sqrt(394872394879847293847)
477
>>477<<