2016-08-04 85 views
0

我有一臺機器,我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 
       } 
    } 
} 

回答

0

你可能想是這樣的(未經測試)

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 
    } 
}