Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

in Tcl/tk, How can I redirect stdout to a text widget?

457 views
Skip to first unread message

Hans Yin

unread,
Dec 23, 2004, 2:29:22 AM12/23/04
to
I already wrote a tcl script. there are many output information sent
to stdout in the script. Now I'm using TK to optimize this script, I
hope to redirect all output information to a text widget, How can i do
it?

I tried to rediect output information to a file, it's OK. then I want
to use "fileevent" command to trace the file's action and then send
new information to a text widget. but system say that "filehandle
cannot be read" error. I think that the reason should be the file is
open for "w" and cannot be read. How can i do it?


close stdout
set file_a [open "testfile" "w"]
fileevent $file_a readable Log # this Log procedure write
information to a text widget.


Any responses will be very appreciated. thanks.

Arjen Markus

unread,
Dec 23, 2004, 5:04:34 AM12/23/04
to

I understand that you have run the program and redirected its
output to a file. In that case:

# Create the widget (I leave the scrollbars to you)

pack [text .t]

# Read the file and put it in the text widget

set infile [open "testfile"]
set contents [read $infile]
close $infile
.t insert end $contents

If you want to catch the output while the program is running,
you indeed need the fileevent command:

set infile [open "|program"]

fileevent $infile readable Log

proc Log {infile} {
if { [gets $infile line] >= 0 } {
.t insert end "$line\n" ;# Add a newline too
} else {
# Close the pipe - otherwise we will loop endlessly
close $infile
}
}

NOTE: this is merely an illustration - I have not tested this
fragment.

Regards,

Arjen

Ahran

unread,
Jan 5, 2005, 3:17:58 PM1/5/05
to
If all output from your script is generated with "puts" you may just
want to redefine its behavior when doing your optimizations.

if {[info exists env(DEBUG)] && [catch {package present Tk}] == 0} {
rename puts tcl_puts
proc puts {args} {
# put special code here to send data to the text widget
# also print to the screen
uplevel 1 tcl_puts $args
}
}

I like to define my own proc for debugging that can be configured to do
different things based on the context. For example output can be
supressed in a production version of the script but turned on for
debugging.

if {[info exists env(DEBUG)]} {
if {[catch {package present Tk}]} {
proc debug {args} {# do something here}
} else {
proc debug {args} { eval puts $args }
}
else {
proc debug {args} {# do nothing}
}

-Ahran

0 new messages