Neil Madden <nem@cs.nott.ac.uk> wrote:
> I'll set the ball rolling with my favourites:
> [fileevent] (...) is a gem. Tcl's event loop was the first aspect
> of Tcl I ran across that both confused and amazed me when I was
> learning.
One particular use I just came across recently was like this:
I had a program doing "heavy math" (actually bigint math in 8.5,
which is another one of my favourites), and worked in an
endless loop, usually only writing out sparse progress-type
information.
Now, if at some time I wanted the current status, I'd have to
"interrupt" it. Tcl, not being the best in interrupt-handling,
(at least unless using tclx,...) helped me with its fileevents:
###################################################################
proc show {{b 0}} {
# parameter b (with fall-through semantics :-)
# always: show some app-specific information.
# 2 ... consume&discard the line that triggered the fileevent, then
# 1 ... read more lines and handle them until empty, then
# 0 ... just continue
puts "app-specific status-display..."
# show a prompt, and read commands:
set line ""; for {set i 0} {$i<$b-1} {incr i} {gets stdin}
if {$b} { puts -nonewline "> "; flush stdout; gets stdin line}
while {$line ne ""} {
# "execute" line: parse app-specific commands, or just
# execute it as tcl-code through eval/uplevel/...
puts [catch {uplevel #0 $line} msg; set msg]
puts -nonewline "> "; flush stdout; gets stdin line
}
}
fileevent stdin readable [list show 2]
#... and then in the main body:
while {1} {
# do one step of the endless calculations ...
set interimsresult [do_one_iteration]
if {$interimsresult eq "very interesting"} {
show 1; # stop for prompt
} elseif {$interimsresult eq "interesting"} {
show 0; # output info, but continue
} else {
update; # this is where "show" gets called, once I press <Return>
}
}
#...
##################################################################
and if the script is then called with some readline-wrapper
tool, (e.g. rlwrap, by Hans Lub), you can even enjoy history
editing on those prompts :-)
PS: this example is for non-GUI scripts. with tkcon or a real
application-GUI it is usually even easier to achieve the effect.
Received on Sun Apr 30 02:50:27 2006