2015-06-12 2 views
0

Я пытаюсь получить доступ к переменной в цикле while в ожидании, но я продолжаю получать ошибку, чтобы эта переменная не существовала. Код в вопросе:Нет такой переменной при использовании while Loop in Expect

#!/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) 

Я уверен, что я делаю что-то невероятно глупое, но я не могу понять это для жизни меня. Спасибо за помощь в продвижении!

ответ

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, так {$initTime - $currentTime > 300} никогда не будет правдой, так что ваш цикл будет бесконечным.

+0

Прежде всего, большое вам спасибо за то, что нашли время, чтобы ответить - это было очень полезно, увидев, что я был в левом поле. Яркая отладка была ключевым здесь, поскольку он показал, что вход, который я получал, не начинался с цифр, которые я ожидал, а скорее из новой строки, поэтому мой совпадение (как вы точно указали) не совпало. Я также обновил команду set, чтобы быть синтаксически правильной. Наконец, я обновил имена переменных от initTime и currentTime до startTime и previousTime соответственно, чтобы сделать его немного более ясным для будущих разработчиков, что время находится в обратном хронологическом порядке – dthagard