在期望中使用While循环时没有这样的变量

时间:2015-06-12 21:35:52

标签: tcl expect

我试图在期望中访问while循环中的变量,但我不断收到变量不存在的错误。有问题的代码:

#!/usr/bin/expect
spawn ./simulator.sh
set timeout 1

...<extra code>...

# Return the time in seconds from epoch
proc getTime {year month day hour minute} {
    set rfc_form ${year}-${month}-${day}T${hour}:${minute}
    set time [clock scan $rfc_form]
    return $time
}

# Get a handle to the file to store the log output
set fileId [open $filename "a"]
# Get one line at a time
expect -re {.*the number of lines from the debug log file to appear on one page.*}
send "1\r"
# Get the initial time stamp and store the first line
expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
    puts -nonewline $fileId $expect_out(0,string)
    set initTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
}
send "1\r"
# Iterate over the logs until we get at least 5 minutes worth of log data
while { true } {
    expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
        puts -nonewline $fileId $expect_out(0,string)
        set currentTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
    }
    # 300 = 5 minutes * 60 seconds
    if { $initTime - $currentTime > 300 } break
    expect -re {.*enter.*}
    send "n\r"
}

...<extra code>...

我得到的错误是:

$ ./test.sh
the number of lines from the debug log file to appear on one page1
201505151624.00 721660706 ns | :OCA (027):MAIN (00) | CONTROL |START LINE
enter1
201505151620.00 022625203 ns | :OCA (027):MAIN (00) | CONTROL |com.citrix.cg.task.handlers.ADDeltaSyncHandler:ThreadID:1182, Delta sync on:activedirectory2
entercan't read "initTime": no such variable
    while executing
"if { $initTime - $currentTime > 300 } break"
    ("while" body line 7)
    invoked from within
"while { true } {
        expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
                puts -nonewline $fileId $expect_out(0,string)
                set currentTime $expect_o..."
    (file "./test.sh" line 42)

我确定我做了一件非常愚蠢的事情,但是我无法理解我的生活。感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这种期望模式不匹配:

expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} {
    puts -nonewline $fileId $expect_out(0,string)
    set initTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)
}

你会知道它是否匹配,因为你会得到一个语法错误:set命令只接受一个或两个参数,你给它6。

exp_internal 1添加到spawn命令之前的一行,并期望会显示详细的调试信息,让您知道您的模式是如何匹配的。

要解决set语法错误,您可能需要

    set initTime [getTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string)]

此外,在if条件下,请注意$initTime 小于 ,因此$currentTime永远不会成为现实,所以你的循环将是无限的。