Expect like syntax in Python
Albert Hofkamp
hat at se-46.wpa.wtb.tue.nl
Tue Feb 5 11:36:12 EST 2002
On Sun, 3 Feb 2002 00:25:14 -0800, Guy Gascoigne - Piggford <guy at wyrdrune.com> 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. In expect I
>can write something like this:
>
>expect {
> -re "ast login" {
> pass
> }
> -re "ogin" {
> send user
> }
> -re "sword" {
> send password
> }
>}
A known problem :-)
I also already noticed that the existing Expect-like thingies are not much help
here, they also mangle the order of the patterns and the actions.
I have been thinking that the following should be possible:
x = ExpectMatcher() # A random name, needs some more thought
... # do some initing stuff, start up a sub-process, connect that to x, etc
while not x.ismatched():
if x.trymatch('ast login'):
pass
elif x.trymatch('ogin'):
send user
elif x.trymatch('sword'):
send password
There are at least 2 options for implementation (but I haven't had the
opportunity to implement either of them).
1) (stupid way)
The x object reads data in the x.ismatched() method. If it has 'enough', it
returns false. Python then executes the x.trymatch() methods. In the method,
you compare the imput with the argument. If it matches, you set a flag that
x.ismatched() should return true on the next call, followed by returning
true (so the if test succeeds).
If all x.trymatch() calls fail, Python executes the 'x.ismatched()' again,
given you a chance to read more data.
2) (intelligent way)
The x.ismatched() returns false in the first call. Python then executes the
if, and as a result, all the x.trymatch() calls. Store the patterns, and
return false to all of them.
On the second call to x.ismatch(), you have a list of patterns, so you can
wait until you have seen a pattern match.
At that moment, return false again, and now return false to all x.trymatch()
methods, except the one that matches.
Python handles the code in the if branch at that point, and returns to the
while.
On the 3rd call to x.ismatched() return true.
(the above scheme should be extended to include time-out)
There are probably other/better implementations possible, I haven't really
considered alternatives except the above 2.
>Am I missing something? I'm fairly new to python but I don't see a way to
Probably not. I took me a few months and a few tricky twists to come up with
the above.
Although the solution seems sound to me, I haven't really tried to implement it.
Albert
--
Constructing a computer program is like writing a painting
More information about the Python-list
mailing list