Expect like syntax in Python

Jeff Shannon jeff at ccvcorp.com
Mon Feb 4 17:18:39 EST 2002


Guy Gascoigne - Piggford wrote:

> I'm trying to find a way to write something like expect in a python module,
> and I'm having trouble getting the syntax the way that I want.
>
>         while 1:
>             try:
>                 if self.expect( ( "ast login", 0 ),
>                                 ( "ogin", self.send_user ),
>                                 ( "sword", self.send_password ),
>                                 ( "\$", "done" ) ) == "done":
>                     break
>             except IndexError:
>                 skipcount += 1
>                 if skipcount == 2:
>                     raise IndexError

I'm not specifically familiar with expect, and I don't know if this will meet
with your requirements/preferences, but I'd be really tempted to replace your
self.expect() call with a dictionary, preloaded with functions.

expectdict = { "ast login": None,
                "ogin": self.send_user,
                "sword": self.send_password
                # ... etc,etc.
                }
if self.expect(expectdict):
    # ....


> Where send_user and send_password are separately defined functions.  What I
> really want to be able to do is to define the action beside the pattern,
> calling short functions that are defined separately makes it harder to read
> and trickier to follow exactly what is happening.  I've also played around
> with just returning an index, but that also gets ugly as the list of
> possible patterns gets larger.

Personally, I find that clearly named functions make more sense than short
anonymous ones;  if the function is well named, then it's easy to guess what it
does, and it's easy to find if you need more detail.  Having the function
definition separate from the list/dict then makes it easier to read the
list/dict, so you can see *what* patterns are being triggered.  Using a
dictionary like I suggested above, as (in essence) a jump table, makes
everything easy to find and keep track of.  Of course, that may just be me, and
YMMV.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list