Nocturn
Nocturn

Reputation: 321

How to iterate over several expected lines

I'm trying to parse some output from a CLI and iterate over it. The output is something like the following, and I want to iterate over each id to do more stuff with those objects.

OVM> list ServerPool
Command: list ServerPool
Status: Success
Data:
id:123456789 name:pool1
id:987654321 name:pool2

I was trying the following code but for some reason it hangs after printing the second ID. I think it has something to do with exp_continue, but I don't understand expect too well. Also, I'm doing this straightforward solution for the case of having only 2 ids cause I don't know how to generalize it and get several lines at a time to iterate over them later and send more commands.

I tried adding an exit after the second id was printed but it was useless, it's like it tries to keep expecting stuff and hangs there. I have no idea how to cancel the exp_continue at that point.

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

Upvotes: 1

Views: 81

Answers (1)

pynexj
pynexj

Reputation: 20797

See following example:

% 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:567890123 name:pool5
id:678901234 name: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:567890123 name:pool5
id:678901234 name:pool6
OVM> other command
==== result: ====
id=123456789 name=pool1
id=234567890 name=pool2
id=345678901 name=pool3
id=456789012 name=pool4
id=567890123 name=pool5
id=678901234 name=pool6
%

Upvotes: 1

Related Questions