2016-04-25 37 views
1

我想解析CLI的一些輸出並遍歷它。輸出結果如下所示,並且我想遍歷每個id以對這些對象做更多的事情。如何遍歷幾個預期的行

OVM>列表ServerPool
命令:列表ServerPool
狀態:成功
數據:
ID:123456789名稱:POOL1
ID:987654321名稱:POOL2

我試着下面的代碼,但由於某種原因它打印第二個ID後掛起。我認爲這與exp_continue有關,但我不太理解。另外,對於只有2個ids的情況,我正在做這個簡單的解決方案,因爲我不知道如何推廣它,並且一次獲得幾行以迭代它們併發送更多命令。

我試着在第二個ID被打印後添加一個退出,但它沒用,它就像它試圖保持期待的東西,並掛在那裏。我不知道該如何取消exp_continue。

expect "OVM> " { 
    send "list ServerPool\r" 
    expect { 
     -re " id:(.*?) (.*?)\n\r" { 
      send_user "$expect_out(1,string)\n"; exp_continue 
     } 
     -re " id:(.*?) (.*?)\n\r" { 
      send_user "\n$expect_out(1,string)\n"; 
     } 
    } 
} 

send "exit\r" 
expect eof 
+0

爲什麼你有相同的正則表達式兩次?你可以添加超時來實現期望的例程。 – Ashish

+0

這兩個id是同時到達還是一次(發送一些命令後接收到第一個id後)? – Sharad

+0

id列表一次。如果我只使用一個期望,正如你所知,它只需要第一個ID。我想知道如何獲取id列表,比如在數組或其他東西中,然後在循環中稍後使用它,以發送其他需要它們的命令。 – Nocturn

回答

1

見下面的例子:

% cat foo.exp 
spawn -noecho cat file 

set idNames {} 
expect { 
    -re {id:([0-9]+) name:([[:alnum:]]+)} { 
     set idName [list $expect_out(1,string) $expect_out(2,string)] 
     lappend idNames $idName 
     exp_continue 
    } 
    "OVM>" {} 
} 

send_user "==== result: ====\n" 
foreach idName $idNames { 
    lassign $idName id name 
    send_user "id=$id name=$name\n" 
} 
% cat file 
OVM> list ServerPool 
Command: list ServerPool 
Status: Success 
Data: 
id:123456789 name:pool1 
id:234567890 name:pool2 
id:345678901 name:pool3 
id:456789012 name:pool4 
id:56789name:pool5 
id:6789name:pool6 
OVM> other command 
% expect foo.exp 
OVM> list ServerPool 
Command: list ServerPool 
Status: Success 
Data: 
id:123456789 name:pool1 
id:234567890 name:pool2 
id:345678901 name:pool3 
id:456789012 name:pool4 
id:56789name:pool5 
id:6789name:pool6 
OVM> other command 
==== result: ==== 
id=123456789 name=pool1 
id=234567890 name=pool2 
id=345678901 name=pool3 
id=456789012 name=pool4 
id=56789name=pool5 
id=6789name=pool6 
%