Sleeping

In the previous section, I showed two ways to get Expect to sleep for a while. Either way is a little painful. Using exec to sleep for a second is a tad expensive. Because of the overhead in creating a new process—inherent in exec—the actual time slept can be significantly greater than one second. The second way requires the “borrowing” of a spawned process. Although this works, it is possible to imagine unintended consequences, such as missing an eof when the spawned process unexpectedly closes the connection while the script is sleeping. In Chapter 20 (p. 482), I will show that there is a time and place for this style of sleeping.

Expect provides a command called sleep that avoids all of the complications I just mentioned. sleep does not require an existing spawned process nor does it create a new process. It is called with a single argument describing how many seconds for which to sleep. For example, the following command sleeps two seconds:

sleep 2

Fractional seconds are also permitted. The following command sleeps for two and a half seconds.

sleep 2.5

Any nonnegative floating-point argument is acceptable. As with the UNIX sleep command, the time slept may be slightly longer than requested.

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.