Matching Patterns From The Spawned Process

Output from the spawned process can be matched by using the -o flag. (Think of the “o” as standing for the “opposite” or “other direction”.) The following command translates unix into eunuchs, vms into vmess, and dos into dog.

interact {
    -o
    "unix" {send_user "eunuchs"}
    "vms"  {send_user "vmess"}
    "dos"  {send_user "dog"}
}

All the patterns before the -o apply to the user keystrokes. All the patterns after the -o apply to the spawned process. For example, the following command is similar to the previous one except that if the user accidentally types one of the humorous nicknames, it is translated back to the correct name. Notice that the first three actions use send to send to the spawned process. The latter three actions use send_user to send to the user.

interact {
    "eunuchs {send "unix"}
    "vmess   {send "vms"}
    "dog     {send "dos"}
    -o
    "unix" {send_user "eunuchs"}
    "vms"  {send_user "vmess"}
    "dos"  {send_user "dog"}
}

This example is artificial and may not seem to make a convincing case for using -o. In practice, matching output from a spawned process almost always requires using regular expressions, in part because process output can be very verbose.

Earlier I said that regular expressions are hard to use from interact. That is only true when reading keystrokes from users. Spawned processes, on the other hand, never do editing so the associated complexities disappear. Regular expressions are an extremely convenient way of matching output from spawned processes. ...

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.