The expect_background Command

It is possible to have actions execute whenever input arrives and matches a pattern. This is accomplished using the expect_background command. Patterns declared this way are called background patterns. These patterns can match whenever the Tk event loop is active. This is similar to the way Tk’s bind command works.

Contrast expect_background with expect. Althought only a single expect command can be active at any time, any number of background patterns can be active simultaneously.

The expect_background command takes the same arguments as the expect command. Both commands also handle spawn ids in the same way. So by default, expect_background associates patterns with the current spawn id. Other spawn ids are associated by using the −i flag.

For example, the following command adds any input received from spawn id $shell to the end of the text widget ".text“.

expect_background −i $shell -re ".+" {
    .text insert end $expect_out(0,string)
}

The expect_background command returns immediately. However, the patterns are remembered by Expect. Whenever any input arrives, it is compared to the patterns. If they match, the corresponding action is executed. The patterns are remembered until another expect_background is entered for the same spawn id. For example, the following command effectively cancels the previous expect_background command:

expect_background −i $shell

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.