Ian Ooi
Ian Ooi

Reputation: 1693

Is there a way to expect output without removing it from the buffer in Tcl expect?

I'm looking for some sort of functionality to "peek" at stdout without removing it from expect's buffer so it can be read in by another expect command. Alternatively, is there a way to put it back in the buffer after reading it?

EDIT: Was asked for some code, it's basically a shell prompt similar to:

(prompt) bad_command_that_was_sent
error message
(prompt) successful_command_that_was_sent
(prompt) other_successful_command
long barf of data that has
very little consistency
and almost no way to tell when it\'s
about to end as the prompt just shows
up again suddenly but I really want to save
it and parse it.
(prompt) 

And right now i'm looking at it like this:

expect {
    -re "Error message regex" {error handling part}
    -re "Prompt regex" {anything I need to do with successes}
}

I'm currently using a workaround where I send an extra newline (send "command\r\r") which gets me 2 prompts to detect, but this isn't ideal, and is/has been actually causing some bugs.

Upvotes: 1

Views: 740

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

If you want to capture all the command output, excluding the prompt:

set prompt_re {\(prompt\) $}
send -- "other_successful_command\r"
expect {
    -re $err_re {handle error}
    -re "(.+)$prompt_re" {
        doSomethingWith $expect_out(1,string)
    }
}

If you're expecting a ton of data, look into the match_max command.


So you don't know when you get an error or not. I'm going to assume that the remote system is a bourne-type shell: execute the command, capture the output, query the exit status, then judge the success/failure of the command.

send -- "some command\r"
expect {
    -re "(.+)$prompt_re" {
        set commandOutput $expect_out(1,string)
        send "echo \$?\r"
        expect -re "(\\d+)\\s+$prompt_re"
        set exitStatus $expect_out(1,string)
        doSomethingWith $exit_status $command_output
    }
}

Upvotes: 1

Related Questions