Main Content

Should we cover expect and/or Tk on our public Tcl courses?

Archive - Originally posted on "The Horse's Mouth" - 2011-05-11 06:24:51 - Graham Ellis

A sizeable minority of our Tcl course delegates use the expect and / or tk extensions. And on our Tcl courses we handle the two differently. For Expect, we include some coverage in our standard agenda, running if required an hour or two into the evening of starting early in the morning to ensure substantial coverage if it's required. For the Tk toolkit, we also include a brief demonstration on the main course, but will then add an extra day or two - a whole extra course - for people who need it. That's because Tk includes a very large number of extra commands and facilities, whereas expect adds a great deal in a few extra commands.

This week, expect is something of a side issue - so a brief demo at the end of yesterfay afternoon was all that was needed. I used the example of wishing to check a series of hosts (sequentially) with ping, and report back on the round-trip time to each. Full source code at [here]

expect is Tcl ... with extra commands, so a foreach loop through a series of hosts is the natural way to test each host in turn without repeating code:

  foreach mysite {www.wellho.net wellho.net www.wellho.co.uk www.firstgreatwestern.info} {

Within each itereation, we start off a ping progess through the spawn command:

  spawn ping -c 3 $mysite

and wait for reply text to include the words "round-trip" which comes late in the response:

  expect "round-trip"

We then use a regexp to extract the vital data we want to report froma everything that expect has dumped into a buffer thats avaulable to us, and report it withing a puts command:

  regexp {time=([0-9]+\.[0-9]+)} $expect_out(buffer) all trip
  puts "$mysite came back with a trip time of $trip"


Result?

  munchkin:tclmay11 grahamellis$ expect xpx
  www.wellho.net came back with a trip time of 21.070
  wellho.net came back with a trip time of 164.911
  www.wellho.co.uk came back with a trip time of 18.176
  www.firstgreatwestern.info came back with a trip time of 30.522
  munchkin:tclmay11 grahamellis$

As always, the devil is in the detail; my program will fail if any of the hosts isn't reachable doesn't respond, and I could add code to deal with that - the facilities are there. However, that would muddy the first training example, and in any case if the program's run and fails that's an indication in its own right that you have a problem in this case.

Tcl (and expect) course details - [here].