如何在Expect的while循环中实现“后备条件”?

如何在Expect的while循环中实现“后备条件”?

问题描述:

我有一台机器,我telnet到,并通过“ctrl + C”,直到我看到提示。 ctrl + C可能不总是工作,所以我必须每5秒后尝试,直到我看到我的预期输出($提示)。如何在Expect的while循环中实现“后备条件”?

如果我没有收到$提示符,如何确保我可以有效地重试while循环?此代码是否低于最佳实践?我担心的是,我不知道当“ctrl + C”失败时我会得到什么,它可能是任何东西,除非是$提示符,否则它必须被忽略。

while { $disableFlag == 0 } { 
    send "^C\r" 
    expect { 
       "*$prompt*" { 
        puts "Found the prompt" 
        sleep 5 
       } 
       "*" { 
        set disableFlag 1 
        puts "Retrying" 
        sleep 5 
       } 
    } 
} 

你可能想是这样的(未经测试)

set timeout 5 
send \03 
expect { 
    "*$prompt*" { 
     puts "found the prompt" 
    } 
    timeout { 
     puts "did not see prompt within $timeout seconds. Retrying" 
     send \03 
     exp_continue 
    } 
} 

# do something after seeing the prompt 

\03是CTRL-C八进制值:见http://wiki.tcl.tk/3038

如果要最终摆脱困境:

set timeout 5 
set count 0 
send \03 
expect { 
    "*$prompt*" { 
     puts "found the prompt" 
    } 
    timeout { 
     if {[incr count] == 10} { # die 
      error "did not see prompt after [expr {$timeout * $count}] seconds. Aborting" 
     } 
     puts "did not see prompt within $timeout seconds. Retrying" 
     send \03 
     exp_continue 
    } 
}