expect, expect_before and expect_after
Posted by admin (Graham Ellis), 22 December 2002With the expect extension to Tcl, and Tcl/Tk, you can use Tcl to start ("spawn") and control (though a series of "send" and "expect" commands) an application which is designed for a human operator rather than to be controlled by another process. Expect is a great tool for automating those awkward jobs that you have to do from the keyboard time and again!
When you're about to write an expect script, you should start by running the application that you're automating manually, and make a careful note of the dialogue - what output the program produces, and what you respond to it. You can then program the sequence quite easily.
Of course, applications don't always run perfectly. If you're automating, let's say, an FTP session it could be that one day the server isn't available. The human operator can cope easily, but your expect script will have to be programmed as to what to do if it gets an unexpected message, an end of file, or a timeout where the target application hangs.
Rather than add all the alternatives into every expect command in your program, you can make use of expect_before and expect_after. These allow you to set up alternative sequences that every subsequent expect command in the currently spawned process will react to in addition to the ones that you've explicitly written into the expect command. Where the returned sequence from the spawned command matches several alternatives, the order of priority taken is
Now - one word of caution. You should specify any expect_before and expect_after commands AFTER you have spawned the process you wish to control. Expect can control multiple spawned processes, and if you specify your _befores and _afters at the wrong point, you can end up applying them to the wrong process.
If you have no spawned process at all and you expect_before, you're liable to get erratic results - for example, an application which runs interactively but fails from crontab, or one which works on one release of an operating system but fails on the next release. Very hard problem to identify if you're not aware of the risk!
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho