Version 1 of Changing stdout, redefining puts and avoiding console show

Updated 2014-02-01 17:25:51 by RLE

Zipguy 2014-01-31 - You can find out my email address by clicking on Zipguy.

This started in Tkchat when I had a problem on Windows, but it does highlight some useful things, namely, nice short illustrations of transchan and refchan. I'd never even thought about channels, nevermind transchan and refchan. What I said, in chat, was something like 'I'm thinking of writing a Bwidget to replace the puts function in a namespace/package combo', and what I got back was an answer that puzzled me. It was 'Maybe you can also close stdout and then open a reflected channel to catch everything that's being puts'ed to stdout'. So instead of asking a question, I thanked everyone in chat. Then I got two teriffic answers, totally different, by two different people in chat a few minutes later.

Here's the first one which was called 'transforming stdout' (using chan push):

# see http://wiki.tcl.tk/21282 (chan push)
namespace eval totk {
  proc initialize args {info procs}
  proc finalize args {}
  proc clear args {}
  proc flush {handle} {
    flush $handle
  }
  proc write {handle data} {
    .t insert end $data
  }
  namespace export *
  namespace ensemble create
}
 package require Tk
 pack [text .t]
 
 chan push stdout totk 

and the second one which was called 'Replacing stdout'

    package require Tk
    pack [text .t]
     
    namespace eval refchan {
    namespace ensemble create -map {
    initialize init
    finalize close
    watch watch
    write write
    }
    }
     
    proc refchan::init {id mode} {
    return {initialize finalize watch write}
    }
     
    proc refchan::finalize {id} {
    }
     
    proc refchan::watch {id spec} {
    }
     
    proc refchan::write {id data} {
    .t insert end $data
    return [string length $data]
    }
     
    close stdout
    set fd [chan create write refchan]
    fconfigure $fd -buffering line
     
    puts "Hello, World!"
    parray tcl_platform

I tried the first one. Lo and behold, I used it in my program ezsdx - a small frontend for sdx and it worked great! Needless to say, I was extremely happy with that. This is what ezsdx looked like, once I first got it working:

http://www.geocities.ws/thezipguy/misc/EasySDX_v098d_WrapnRun.png

Notice, above, that all my puts statements are not it a seperate window, but in a text item, in a frame in my main application. Way to cool! And even better, SDX's puts are there too! So I did a lot of work on ezsdx, and have a much better version of it, on Windows (7). It gets rid of the problem of havng to switch back and forth, imbetween the app's window and the console window, to see if your program worked, or for one that you haven't written, like SDX, which does uses puts completely.

Even better you can use colors in text widgets, like this [L1 ]

The second solution looks very interesting too! Haven't tried it yet.

Comments are welcome.