(转)A Tcl/Tk and Expect Tutorial

  1                      Landmark Graphics Corporation
  2                     World Wide Technology Conference
  3
  4                              Houston, Texas
  5
  6                             December 11994
  7
  8
  9                                     
 10                                     A
 11                             Tcl/Tk and Expect
 12                                  Tutorial
 13
 14
 15               by:  Will Morse
 16                    BHP Petroleum 
 17
 18Copyright 1994 Will Morse.  Permission is given to freely copy and
 19distribute this paper as long as there is no charge except real and
 20actual mechanical copying costs and as long as this notice is kept
 21with each copy so others may copy it as well.
 22
 23The opinions expressed are the author's own and do not necessarily
 24reflect the opinions or policies of The Broken Hill Proprietary
 25Company, Limited, or its various divisions.  Your milage may vary.
 26 INTRODUCTION:
 27
 28     Shell scripts are the frequent tool of Landmark systems
 29     administrators.  Whether Bourne shell, C-shell, or Korn shell,
 30     shell script programs have distinct limits.
 31
 32     *    They usually run in an Xterm window, and require the user
 33          to have some ancillary knowledge of Unix commands.
 34
 35     *    They do not take advantage, or take only the most trivial
 36          advantage, of the mouse.
 37
 38     *    They do not have the advantages of scroll bars, radio
 39          buttons and so on, so they must ask questions and take
 40          user input, even if the default is acceptable.  For some
 41          programs, this can be twenty or more questions, even if
 42          the answer is just a tap of the enter key.
 43
 44     *    It is unusual to have these programs "hanging" on the
 45          Command Menu (launcher).
 46
 47     In addition,  shell script programs cannot have a useful
 48     two-way dialog with a program such as bcm2d or zap.  If you
 49     want to run ten bcm2d jobs in a shell script, you still have
 50     to watch the screen and every now and then respond to
 51     questions.  Most systems can not run several zap jobs at once. 
 52     It would be nice to be able to "stack" them in a shell script
 53     and run them sequentially over night.
 54
 55     Tcl/Tk and expect act on the level of shell scripts, but
 56     provide the capability of drawing X-windows "widgets" and of
 57     operating programs without a human constantly watching.
 58
 59     As a systems administrator or data administrator, these
 60     programs can save you time and increase your productivity
 61     because you can make many simple, and even complex, operations
 62     available to the geologist / geophysicist user directly.  You
 63     can also save time by being able to run many data loading and
 64     other processing operations unattended overnight.
 65
 66     All these programs are FREE.  The most you might pay is $60 or
 67     so for a CD-ROM containing the programs which you can then
 68     install on your system.  There are also several consulting
 69     firms in the Houston area (see page 19) that will do all the
 70     installation and give you training, for a fee, of course.
 71
 72     In this tutorial, we will discuss:
 73
 74          Definitions                        page 3
 75          Seismic / SeisWorks applications   page 4
 76          A Simple Expect Program            page 6         
 77          A Simple Tcl/Tk (wish) Program     page 8
 78          Basic Tcl                          page 10
 79               Variables                          page 10
 80               Set                                page 10
 81               Embedded Execution                 page 10
 82               Arithmetic                         page 11
 83               If-then-Else                       page 11
 84               Loops                              page 12
 85               Files                              page 12
 86               Procedures                         page 13
 87               Regular Expressions                page 13
 88          A Simple Expectk Program           page 15
 89          Manuals and Documentation          page 17
 90          Where to Get It                    page 18
 91          Where to Get Support               page 19
 92 DEFINITIONS:
 93
 94     Tcl       pronounced "tickle"is a fairly simple and
 95               straight forward computer language similar to a
 96               shell language.  Tcl stands for Tool Command
 97               Language.
 98
 99     Tk        is a set of libraries that can be used by a string
100               oriented computer language such as Tcl to draw
101               X-windows "widgets" such as list boxes, menus, and
102               so on.  Tk is most often used with Tcl, but will
103               also work with other languages such as perl and
104               scheme.
105
106     expect    is an extended version of Tcl which can serve as a
107               "robot operator" to run certain kinds of programs,
108               in particular programs like Landmark's bcm2d and
109               bcm3d and zap.
110
111     expectk   is a version of expect that uses the X-windows
112               drawing capability of Tk.
113
114     wish      is a combined interpreter (shell) for Tcl and Tk. 
115               wish stands for "windowing shell".
116
117     widget    a component of an X-windows window.  Examples of
118               widgets are: scroll-bars, select lists, push
119               buttons, radio buttons, pull-down and pop-up menus. 
120               A special kind of widget is the "canvas", which is
121               used for diagrams, graphs, and other drawings.
122
123     Tcl, while it has many merits, is generally not of interest to
124     this audience except in combination with one of the other
125     programs.
126
127     Tcl/Tk is dramatically easier than C, C++and the Motif and
128     X libraries.  Still, it is not the easiest place to start of
129     this group.  We will cover some of the basic ideas in this
130     paper that will get you to where you can read and understand
131     the manuals.
132
133     expect is the easiest program in the group.  You can write
134     useful scripts in expect without understanding Tcl at all.  A
135     little Tcl will help you expand these scripts into powerful
136     tools.
137
138     expectk is not hard, but combines elements from the other
139     programs so it is best to learn at least a little about Tcl,
140     Tk, and expect before getting into expectk.
141
142 SEISMIC AND SEISWORKS APPLICATIONS:
143
144     Applications written in these languages that are related to
145     seismic interpretation and to SeisWorks include:
146
147     *    run.bcm2d and run.bcm3d
148
149          These programs are used to build a shell script that can
150          run bcm jobs at night with no operator attention.
151
152     *    License signup sheet.
153
154          This on-line signup sheet lets users sign up for licenses
155          at specified times.  Users can plan their usage without
156          having to go to a central paper signup sheet.  With the
157          "Check licenses" feature, a person who has signed up for
158          a license can find out if someone else is "borrowing"
159          some of their time.
160
161     *    Eclipse Control Panel
162
163          The Eclipse Reservoir Simulator requires a number of
164          routine questions be answered each time it runs.  The
165          Eclipse Control Panel presents these questions as select
166          boxes, radio buttons, and text entry boxes.  The default
167          answers are pre-selected.  If you want to run the
168          defaults, just click okay.
169
170     *    ZAP-later.
171
172          This program collects the parameters needed to run a ZAP
173          job and allows that job to be run overnight at a
174          specified time.  The user does not have to be logged in
175          to the system at the time the ZAP is run.
176
177     *    Programs like plist, odacheck, and other SeisWorks
178          utilities are easily run in a windows environment with
179          results displayed in list boxes.
180
181     *    CGM Plotting Control Panel
182
183          This program lets the user select paper or transparency
184          media, up to 5 copies, rotated display,  remove after
185          plotting or keep.  There is a feature to help find the
186          CGM file.  A previewer (incorporating gplot, a FREE
187          program) lets the user see the general look of the plot
188          before commiting to paper.
189
190     *    Planimeter
191
192          A simple planimeter program that puts the digitized
193          points in a file the way you want.  
194
195     *    Replacement for launcher.
196
197          This program works like the standard LGC launcher except
198          it lets you specify seperator lines between menus, lets
199          you use icons for selections instead of just text, allows
200          selections to be turned on and off.
201
202     *    GUI's for CWP / SU 
203
204          CWP / SU (Center for Wave Phenomon, Seismic Unix) is a
205          set of free seismic processing programs.  These programs
206          are similar to shell script programs in the way they
207          operate.  Tcl/Tk can provide a Graphic User Interface to
208          these programs and make them much easier to use.
209 A SIMPLE EXPECT PROGRAM:
210
211     Expect is basically a "robot operator" that executes a program
212     for you.  When this program puts a message out, thinking it is
213     going to you as the program user, expect intercepts that
214     message and gives the program the appropriate reply.
215
216          run.bcm2d
217
218      1   #! /usr/local/bin/expect --
219      2   set timeout -1
220      3   spawn bcm2d [lindex $argv 0]
221      4   expect *number :*
222      5   exec sleep 1
223      6   send "r\r"
224      7   expect "*Ready, or A to Abort :*"
225      8   exec sleep 1
226      9   send "r\r"
227     10   expect eof
228     11   exit
229
230     You can put several instances of this program in a basic shell
231     script and run the program overnight:
232
233          #! /bin/sh
234          run.bcm2d file01.pcl
235          run.bcm2d file02.pcl
236          run.bcm2d file03.pcl
237          run.bcm2d file04.pcl
238               
239          run.bcm2d file17.pcl
240          run.bcm2d file18.pcl
241          run.bcm2d file19.pcl
242          run.bcm2d file20.pcl
243
244     Line 1 is the "shebang" line.  It tells Unix what shell to use
245     to run this program.
246
247     Line 2 turns off the timeout feature.  This feature is useful
248     in programs that dial into remote databases and so on, but not
249     for bcm2d.
250
251     The program runs the bcm2d program using spawn (3).  The part
252     [lindex $argv 0] takes the "zeroth" item from the list $argv
253     and uses that as the file bcm2d processes.  lindex stands for
254     "list index"and, like Unix programs everywhere, 0 is the
255     first item (and in this case, the only item) in the list.
256
257     Every time the program stops to ask what reel number you want
258     to use (4), expect supplies an answer "r" (6).  The * in front
259     and after "number :" tell expect that the question will
260     contain these characters, but that there will be other
261     characters as well.  The \r (6is the return key you would
262     have typed.  There is a 1 second "sleep" (5) between the time
263     the question is asked by bcm2d and the time expect gives the
264     answer because bcm2d is expecting a human to answer and isn't
265     quite ready to listen so quickly after asking.
266
267     Every time bcm2d asks if you are ready (7), expect fills in
268     the "r" (9), once again a sleep (8) with \r for the return
269     key.
270
271     The eof (10is the end of file.  When bcm2d (or any other
272     program) finishes and exits, it closes its standard output
273     file.  expect detects this.  If you did not wait for eof,
274     expect would just quit after answering the Ready prompt (9),
275     and take down bcm2d with it.
276 A SIMPLE TCL/TK (WISH) PROGRAM:
277
278     This simple program executes the Landmark "plist" command and
279     puts the results in a scrollable listbox.  You could easily
280     "hang" this command on the OpenWorks Command Menu (launcher).
281
282     This example has unusual spacing to make it easier to show the
283     various parts of the program, there is no spacing requirement
284     in Tcl/Tk.  The italicized numbers are for the explanation
285     below, they do not exist in the file.
286
287      1   #! /usr/local/bin/wish -f
288      2   wm         title    .  {Landmark Project List}
289      3   wm         geometry .  +250+250
290      4   wm         minsize  .  1 1
291
292      5   label      .label   -text {Landmark Project List} \
293      6                       -font 10x20
294
295      7   frame      .f       -borderwidth 5
296      8   scrollbar  .f.y     -command {.f.list yview}
297      9   scrollbar  .f.x     -orient horiz \
298     10                       -command {.f.list xview}
299     11   listbox    .f.list  -relief sunken \
300     12                       -xscroll {.f.x set} \
301     13                       -yscroll {.f.y set}
302
303     14   pack append .f      \
304     15               .f.y    {right filly} \
305     16               .f.x    {bottom fillx} \
306     17               .f.list {top fillx filly expand}
307
308     18   button     .ok      -text {OK} \
309     19                       -command {destroy .}
310
311     20   pack append .       \
312     21               .label  {top fillx} \
313     22               .f      {top fillx} \
314     23               .ok     {top fillx}
315
316     24   set         fh      [open "|plist" r]
317     25   while       {! [eof $fh]} {
318     26               gets $fh line
319     27               .f.list insert end $line
320     28               }
321
322     Line 1    is the "shebang" line to tell Unix which
323               interpreter to use.
324
325     Line 2    uses the wm command to pass the title to Motif to
326               display on the title bar.
327
328     Line 3    uses the wm command to pass the location on the
329               screen to Motif.  If you do not use this, you will
330               have to click the mouse button to "realize" the
331               window.
332
333     Line 4    gives the minimum dimensions of the window.  This
334               turns on the ability to change the size of the
335               window using the Motif side handles.
336
337     Line 5    Defines a label on the window giving the text and
338               the font.  Note the escaped return.  You cannot
339               just start on the next line.
340
341     Line 7    creates a frame.  A frame is a assembledge of
342               smaller pieces that will be treated as one piece.
343
344     Line 8    describes the vertical scrollbar.  The way this
345               works is that the scroll bar computes a position,
346               them tells .f.list, the listbox, to move to that
347               position.
348
349     Line 9    is the same for the horizontal scrollbar
350
351     Line 11   describes the listbox and associates it with the
352               scrollbars.
353
354     Line 14   "packages" the components of the scroll box, that
355               is, the listbox and the two scrollbars.
356
357     Line 18   creates a "button".  When this button is "pressed",
358               it executes the command.  In this case, the command
359               is to destroy the base widget (named .) which exits
360               the program.
361
362     Line 20   packages the base widget with the label, the frame,
363               and the button.  They are all set to "top" so they
364               will appear in order from the top.
365
366     Line 24   is a Tcl command (see page 12).  It opens a pipe in
367               which it executes the "plist" command.  It sets the
368               filehandle for the result in fh.
369
370     Line 25   is a Tcl command, it tests the end-of-file status
371               for the piped plist command.  As long as there are
372               more lines of output from plist, the program
373               executes the target commands.
374
375     Line 26   is a Tcl command.  gets reads a line from the plist
376               command and puts it in the variable named "line".
377
378     Line 27   inserts the line into the listbox at the end.
379
380     Line 28   closes the while loop.
381
382     The program creates the window and then waits for user to do
383     something.  If the something is moving the scroll bars,  the
384     program executes those commands.  If the something is clicking
385     the OK button, the program exits.
386
387 BASIC TCL:
388
389     Tcl has hundreds of features.  This is a barely adequate
390     overview to help us understand the other programs.
391
392Variables:
393
394     A Tcl variable is any set of letters and numbers, but it is
395     best for the first character to be a letter.  All variables in
396     Tcl are character strings, they only become numbers during
397     arithmetic operations.
398
399     Variables can be in arrays.  env is the array of environmental
400     variables.
401
402                    set home $env(HOME)
403
404Set:
405
406     The set command give a variable a value.
407
408          set pi 3.1415926
409          set name "World Wide Technology Conference"
410
411     Set without a value reports the value that the variable
412     already contains:
413
414          set pi
415
416     returns 3.1415926.  A shorthand way to report a value (and by
417     far the most frequent way to do this, is to precede the
418     variable name with a $:
419
420          set morePi $pi
421
422Embedded Execution:
423
424     Tcl has an embedded execution using square brackets that is
425     basically analogous to the back quote execution in Bourne
426     shell except that embedded execution can be nested in Tcl.
427
428          set a [pwd]
429          set a [sort $list]
430          set a [sort [list $x $y $z]]
431
432Arithmetic:
433
434     The great bulk of arithmetic in Tcl takes place in either the
435     conditions of an if-then-else or in an expr command.  You can
436     not have a command:
437
438          set a $a + 1
439
440     It needs to be:
441
442          set a [expr $a + 1]
443
444     There are some commands which act as though they had an expr
445     command in front of them:
446
447          set a [sin $angle]
448          set a [expr sin($angle)]
449
450     but not
451
452          set a [atan2 $y $x]
453
454     this must be
455
456          set a [expr atan2($y,$x)]
457
458If-then-else:
459
460     The Tcl if-then-else is pretty straight forward:
461
462          if {condition} then {action} else {action}
463
464     This is frequently written:
465
466          if {$a == $b} then {
467               puts "true"
468          } else {
469               puts "false"
470          }
471
472     You must escape the return before the then and the else to
473     write:
474
475          if {$a < $b}   \
476          {
477               puts "true"
478          } \
479          else \
480          {
481               puts "false"
482          }
483
484     This is because Tcl does not have a specific line termination
485     character (such as the semicolon in perl).
486
487For and While:
488
489     These are also pretty straight forward:
490
491          while {condition} {action}
492
493          for {start} {test} {increment} {action}
494
495     For example:
496
497          while {! [eof $file]} {
498               gets $filehandle line
499          }
500
501          for {set i 1} {i < 10} {incr i 1} {
502               set a [expr 10 * $i]
503               puts "$a"
504          }
505
506Files:
507
508     Reading and writing are normally done using the gets and puts
509     commands.  It is not necessary to open STDIN, STDOUT, or
510     STDERR.  Other files must be opened explicitly.  Files are
511     closed implicitly when the program terminates, but you can
512     explicitly close them if you want.  
513
514     File commands include:
515
516          open      note, open needs to be "set xx [open]
517          close     filehandle
518          eof       filehandle
519          gets      filehandle variable
520          puts      filehandle "string with $variables"
521
522     For Example:
523
524          set fhIn  [open "/etc/passwd" r]
525          set fhOut [open "/home/hacker/passwd" w]
526          while {! [eof $fhIn]} {
527               gets $fhIn input
528               puts $fhOut "$input"
529          }
530          close $fhIn
531          close $fhOut
532
533     The file can be a pipe to another program.  This is signified
534     by placing the pipe symbol at the BEGINNING of the command
535     name:
536
537          set fhIn  [open "|cat /etc/passwd" r]
538          set fhOut [open "|wc -l"           w]
539
540Procedures and Subroutines:
541
542     Procedures are defined with the proc statement:
543
544          proc hypot {x y} {
545               set h [sqrt $x*$x+$y*$y]
546               return $h}
547
548     To call a procedure, write the procedure as a statement:
549
550          gets x
551          gets y
552          set hy [hypot $x $y]
553          puts "Hypot = $hy"
554
555     You can give a procedure default values:
556
557          proc maybe {{window .ww}} {
558               toplevel $ww
559               button $ww.b -text 
560          }
561
562     You can execute a Unix command with the exec command:
563
564          set longevity [exec uptime]
565
566     BOTH STANDARD OUTPUT AND STANDARD ERROR will be set into the
567     variable (in this case, longevity).
568
569Regular Expressions:
570
571     No Unix program is complete without at least one regular
572     expression.
573
574     The regexp command handles regular expressions.  This can be
575     in an if statement, such as:
576
577          if [rexexp {^[0-9][0-9]*} $number] then {}
578
579     It can also be used to extract values.
580
581          regexp { *([0-9][0-9]*), *([0-9][0-9]*), *(..*)} \
582              match xLocation yLocation buttonPressed
583
584     This can be greatly simplified using variables:
585
586          set D   "[0-9][0-9]*"    # one or more digits
587          set ANY "..*"            # one or more characters
588
589          regexp " *($D), *($D), *($ANY)" match X Y button
590
591     You could not define the spaces as 
592
593          set WS  " *"
594
595     and
596
597          regexp "$WS($D),$WS($D),$WS($ANY)" match X Y button
598
599     because Tcl would be confused whether $WS($D) was referring to
600     two variables next to each other, or an array variable $WS
601     indexed by $D.
602
603
604 A SIMPLE EXPECTK PROGRAM:
605
606     This program performs a simple action and puts up a
607     "Click to Continue" button to let you know that it finished. 
608
609      1   #! /usr/local/bin/expectk --
610      2   button  .ok    -text {Running Tar} -command exit
611      3   pack    .ok    -fill x -fill y 
612      4   exec    tar   -cvf /dev/rst2 /p?/project1 
613      5   expect  eof
614      6   .ok     config -text {Click to Continue}
615
616     You will want to have the Tk description in place (lines 2 and
617     3) before running the command (line 4or expectk will place
618     a rather annoying default box on the screen until it gets
619     directions on how to fill it. Line 6 is used to change the
620     text on the button.
621     
622     A slightly more useful version of this program would be:
623
624      1   #! /usr/local/bin/expectk --
625      2   wm geometry . +250+250
626      3   wm minsize . 1 1
627      4   button .ok -text {Running The Command}  \
628      5              -borderwidth 10 \
629      6              -relief sunken \
630      7              -state disabled \
631      8              -disabledforeground black \
632      9              -activebackground grey \
633     10              -activeforeground green \
634     11              -fg black \
635     12              -bg pink \
636     13              -font 10x20 \
637     14              -command exit
638     15   pack .ok -fill x -fill y
639     16   set xx [exec $argv ]
640     17   expect eof
641     18   .ok config -state normal \
642     19              -relief raised \
643     20              -bg green \
644     21              -text {Push to Continue}
645
646     This program will run an arbitrary command supplied as an
647     argurement and tell you when it is done.  The program is
648     called by:
649
650          flag.run "ls /p?"
651
652     The double quotes make the ls and the /p? into one argurment,
653     otherwise the program would only execute the ls.
654
655     The program uses a lot of colors basically to demonstrate that
656     they can be used.  It is not necessary to use so many colors.
657
658     Lines 2 and 3 set up the window so that it is only the
659     necessary size.  The default size is rather larger.
660
661     Line 4 gives the initial text.  This text will be changed by
662     line 21.
663
664     Lines 56and 7 set up characteristics of the button.  The
665     borderwidth is used to give the amount of relief the button
666     will have.  The state is disabled so that the user cannot
667     click the button before the program is finished.  Once the
668     prgoram is finished, the state is changed to normal in line
669     18.  The relief is sunken.  The relief is changed to raised in
670     line 19.
671
672     Lines 8 - 12 give colors for various states the button can be
673     in.  Note that there is not an option for disabledbackground. 
674     active means that the mouse pointer is positioned over the
675     button.  The button cannot become active if it is disabled.
676
677     Line 16 is where the command is executed.  The set xx [] is
678     used to capture the output in a string in the program so that
679     is is not displayed on the xterm.
680
681     The config command in line 19 is used to change parameters
682     specified originally in line 4.
683 MANUALS AND DOCUMENTATION:
684
685     Each of these programs has a "man page" that is installed with
686     the program.  This has no additional cost, but has the typical
687     "reminder for people who already know" style of man pages
688     generally.
689
690     The definitive reference for Tcl and Tk is:
691
692               Tcl and the Tk Toolkit
693               John Ousterhout
694               Published by Addison-Wesley
695               ISBN: 0-201-63337-X
696
697     The definitive reference for expect and expectk, and a good
698     resource for Tcl, is:
699
700               Exploring Expect
701               by Don Libes
702               Published by O'Reilly & Associates, 
703               ISBN: 1-56592-090-2
704
705     These books are available at BookStop in Houston and at other
706     fine bookstores.
707
708     The Energy Related Unix User's Group Unix Cookbook contains
709     contributed Tcl/Tk scripts of interest to the petroleum
710     exploration and production technical user.
711 WHERE TO GET IT:
712
713     If you have an Internet connection, all these programs can be
714     obtained by anonymous ftp from
715
716               ftp.cme.nist.gov
717
718     Other sources are CD-ROM's.  Some CD-ROM's are distributed
719     with books.  Two good places to look for these programs are:
720
721               Prime Time Freeware for Unix, $60.00
722               ISBN 1-881957-04-7
723
724               Unix Power Tools, $59.95
725               ISBN 0-679-79073-X
726
727     These books are available at BookStop in Houston and at other
728     fine bookstores.
729
730 WHERE TO GET SUPPORT:
731
732     The best support for all these languages is in the Internet
733     Newsgroup:
734
735                               comp.lang.tcl
736
737     There are at least two companies in Houston that will help
738     with Tcl and Tk on a consulting basis.
739
740          Neosoft
741
742          Paranet
743
744     There are some people in the Energy Related Unix User's Group
745     (ERUUG) in Houston that are using Tcl/Tk and Expect.  To join
746     ERUUG, call Analisa Smith at (713621-0022.
747
748

posted on 2008-08-23 16:57 挑灯看剑 阅读(1076) 评论(0)  编辑 收藏 引用 所属分类: 通信技术

只有注册用户登录后才能发表评论。
<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

公告

【自我介绍】 08年南开大学硕士毕业 最近关注:算法、Linux、c++、高并发 爱好:滑旱冰、打乒乓球、台球、保龄球

常用链接

随笔分类(139)

文章分类

我常去的网站

技术博客(都是大牛)

技术站点

搜索

积分与排名